Add Jetpack-Compose to projects uses API below 21

Viewed 3912

I know that minimum API level 21 is a must for enabling Jetpack Compose in a project.

I want to use JetPack Compose in my existing project. It uses minSdkVersion=17 and I can't add compose dependencies to build.gradle.

uses-sdk:minSdkVersion 17 cannot be smaller than version 21 declared in library [androidx.activity:activity-compose:1.3.0-alpha03]

My goal is to use Compose for users that have Android API >= 21.

How I achieve this goal?

2 Answers

I tried to create a new android-library module (:widget). set minSdkVersion=21 and also configure Compose inside it.

Add :widget to :app module dependencies

dependencies {
    implementation project(":widget")
    ...
}

Override minSdkVersion of all Compose packages in :app's AndroidManifest.xml

<uses-sdk
    android:minSdkVersion="17"
    tools:overrideLibrary="com.example.widget, androidx.compose.ui.platform, androidx.compose.material.icons, androidx.activity.compose, androidx.compose.ui.tooling, androidx.compose.ui.tooling.data, androidx.compose.material.ripple, androidx.compose.foundation, androidx.compose.animation, androidx.compose.foundation.layout, androidx.compose.ui.text, androidx.compose.ui.graphics, androidx.compose.ui.unit, androidx.compose.ui.util, androidx.compose.ui.geometry, androidx.compose.runtime.saveable, androidx.compose.animation.core" />

Finally, define custom-view and return a configured ComposeView as a normal view.

It'll work fine in Android API >= 21

fun myCustomView(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
): View {
    return ComposeView(context, attrs, defStyleAttr).apply {
        setContent {
            Text(text = "Hello")
        }
    }
}

No can do.

It is official, Android studio won't allow you to even create a project with such a configuration which proves it.

Trying to do it manually MIGHT compile but I think the app would most certainly crash if run on a device with API level <21

Related