将 Jetpack-Compose 添加到使用低于 21 的 API 的项目

bei*_*rad 8 android android-manifest android-jetpack android-jetpack-compose

我知道在项目中启用 Jetpack Compose 必须达到最低 API 级别 21。

我想在现有项目中使用 JetPack Compose。它使用minSdkVersion=17但我无法将 compose 依赖项添加到build.gradle.

uses-sdk:minSdkVersion 17 cannot be smaller than version 21 declared in library [androidx.activity:activity-compose:1.3.0-alpha03]
Run Code Online (Sandbox Code Playgroud)

我的目标是为 Android API >= 21 的用户使用 Compose。

我如何实现这个目标?

bei*_*rad 6

我尝试创建一个新的 android-library 模块 ( :widget)。设置minSdkVersion=21并在其中配置 Compose。

添加:widget:app模块依赖项

dependencies {
    implementation project(":widget")
    ...
}
Run Code Online (Sandbox Code Playgroud)

覆盖AndroidManifest.xmlminSdkVersion中的所有 Compose 包:app

<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" />
Run Code Online (Sandbox Code Playgroud)

最后,定义自定义视图并返回配置好的 ComposeView 作为普通视图。

它会在 Android API >= 21 中正常工作

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

  • 它很可能会在 API 17-19 上崩溃 (2认同)