7. Integrating KMP with an Android App
--
Integrating Kotlin Multiplatform (KMP) into your Android app allows you to share code between different platforms. Here’s a step-by-step guide to connecting KMP to your Android app, including accessing shared code in Android project. In this example, we will use the Greeting
class from the shared module in the Android app.
Step 1: Add KMP Shared Module Dependency in Android App
Add the shared module as a dependency in your Android app’s build.gradle.kts file.
File: androidApp/build.gradle.kts
dependencies {
...
implementation(project(":shared"))
}
This line adds the shared
module as a dependency, enabling the Android app to use code from the shared module.
Step 2: Define Compose Plugin Version in libs.versions.toml
Add the Compose plugin version to the libs.versions.toml file.
File: gradle/libs.versions.toml
[versions]
...
compose-plugin = "1.6.10"
[libraries]
...
compose-material = { module = "org.jetbrains.compose.material:material", version.ref = "compose-plugin" }
This defines the version for the Compose plugin, which will be used for the Compose Material library in the shared module.
Step 3: Add Compose Material Dependency in Shared Module
Add the Compose Material library as a dependency in the commonMain source set of the shared module.
File: shared/build.gradle.kts
kotlin {
...
sourceSets {
commonMain.dependencies {
...
implementation(libs.compose.material)
}
}
}
This allows the shared module to use Compose Material components, which can be used across different platforms.
Step 4: Access Shared Code in MainActivity
Import the shared module’s Greeting class and use it within your MainActivity.
File: androidApp/.../MainActivity.kt
import com.example.shared.Greeting
...
Button(onClick = {
val userName = (1..10).map { ('a'..'z').random() }.joinToString("")
insert(User(name = "${Greeting().greet()} $userName"))
}) {
Text(text = "Add User")
}
...
This code imports the Greeting
class from the shared module and uses it within a Button's onClick listener. It generates a random username and combines it with a greeting message from the shared module, demonstrating how shared code can be used in the Android app.
Summary
By following these steps, you have successfully integrated the Kotlin Multiplatform shared module into your Android app. You can now share common code, like the Greeting
class, between different platforms, enhancing code reusability and reducing redundancy.
Testing
Before:
After: