kotlingradleandroid-gradle-pluginkotlin-multiplatformkotlin-gradle-plugin

(KotlinSourceSet with name 'androidMain' not found.) How can I add android as a build target to a Kotlin Multiplatform project


I am trying to add android() as a build target to a Kotlin Multiplatform library so that I can add a specific library for the android target. All the other targets (jvm, linux, ios) work fine, but android seems to have issues, because the KotlinSourceSet is not being create like the others.

That's where I get the error:

KotlinSourceSet with name 'androidMain' not found.

I wonder, do I have to add the SourceSet manually? Am I missing some crucial build step?

Here is my gradle.build.kts

plugins {
    id("maven-publish")
    kotlin("multiplatform") version "1.8.0"

}

buildscript {
    repositories {
        google()
    }
    dependencies {
        classpath ("com.android.tools.build:gradle:4.2.2")
        classpath ("org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.0")
    }
}

group = "zzz.xxxx"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

kotlin {
    jvm()
    linuxX64("linux")
    ios()
    android()

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation("...")
            }
        }
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test")) 
            }
        }
        val jvmMain by getting {
            dependencies {
                implementation("...")
            }
        }

        val androidMain by getting {
            dependencies {
                implementation ("...")
            }
        }

        val jvmTest by getting

    }
}

I tried adding a androidMain folder, but it is not getting recognized as a KotlinSourceSet. Non of the resources online seem to help either.


Solution

  • To add android as a build target your need to setup android-gradle-plugin first.

    With example setting of android plugin gradle.build.kts will be:

    plugins {
        id("maven-publish")
        kotlin("multiplatform") version "1.8.0"
        id("com.android.library") version "7.3.0" // (1) add plugin
    }
    
    //...
    
    // (2) setup plugin
    android {
        compileSdk = 33
    
        defaultConfig {
            minSdk = 24
            multiDexEnabled = true
        }
    
        sourceSets {
            getByName("main") {
                manifest.srcFile("src/androidMain/AndroidManifest.xml")
            }
        }
    }
    

    UPDATE

    Before you are adding Android Gradle plugin: