How to add Jetpack Compose into Kotlin Multiplatform Mobile default template?

January 16, 20222 min read#iOS, #Swift, #Android, #Kotlin, #KMM, #M1

Jetpack Compose and SwiftUI are becoming increasingly popular to create frontend UIs for Android and iOS

With the combination of Kotlin Multiplatform Mobile and Jetpack Compose + SwiftUI, mobile developers nowadays have advanced toolings to create apps for both Android and iOS platforms simutanously.

The default project generated by Kotlin Multiplatform Mobile Plugin for Android Studio doesn’t support Jetpack Compose by default.

I have to adjust some configurations for the androidApp project to be able to use Jetpack Compose in the Android app

Update build.gradle.kts for androidApp project

plugins {
    ...
}

// Added for Jetpack Compose
// Since the project is using Kotlin 1.6.10, we have to use this alpha version of Jetpack Compose as of 16.01.2022 
val composeVersion = "1.2.0-alpha01"

android {
    ....

    // Added for Jetpack Compose
    buildFeatures {
        compose = true
    }
    composeOptions {
        kotlinCompilerExtensionVersion = composeVersion
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies {
    ...

    // Added for Jetpack Compose
    implementation("androidx.activity:activity-compose:1.4.0")
    implementation("androidx.compose.material:material:$composeVersion")
    implementation("androidx.compose.ui:ui-tooling:$composeVersion")
}

Update MainActivity for androidApp

fun greet(): String {
    return Greeting().greeting()
}

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MaterialTheme {
                MainView()
            }
        }
    }
}

@Composable
fun MainView() {
    Column(
        Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = greet())
    }
}

Sample project

You can find all these changes in this sample project


Profile picture

Personal blog by An Tran. I'm focusing on creating useful mobile apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2022