Android项目中使用ComposeUI
首先确认项目环境kotlin版本,以下是本机的版本
使用命令
./gradlew -version
这里kotlin 版本是1.5.31
然后查看build.gradle sdk版本
这里是32 属于低版本
然后需要添加以下配置
buildFeatures {compose = true}composeOptions {kotlinCompilerExtensionVersion = '1.3.0' // Kotlin 1.5.31 对应的 Compose 编译器版本}
注意kotlinCompilerExtensionVersion 不同的kotlin 版本 kotlinCompilerExtensionVersion 对应的版本号不一致,如果是1.8以上的kotlin 版本 对应的版本号 应该是1.4.3 具体网上查询下
然后添加compose 核心依赖库
implementation "androidx.compose.ui:ui:1.0.0"implementation "androidx.compose.material:material:1.0.0"implementation "androidx.compose.ui:ui-tooling:1.0.0"implementation "androidx.activity:activity-compose:1.3.1"
注意,这里本机环境是低版本的kotlinCompilerExtensionVersion 和 sdk 是低版本 用低版本的库,
androidx.compose.ui:ui:1.0.0 如果使用1.4以上 依赖不合 会导致编译不过
添加示例ComposeUI类
import android.os.Bundle
import android.os.PersistableBundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Text
import androidx.compose.runtime.Composableclass CompActivity :ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {MyComposeUI()}}
}
@Composable
fun MyComposeUI(){Text(text = "Hello,Compose")
}