一、概念
1.1 Compose优势
- 由一个个可以组合的Composable函数拼成界面,方便维护和复用。
- 布局模型不允许多次测量,提升了性能。
- Compose可以和View互操作(相互包含对方)。
1.2 声明式UI
APP展示的数据绝大多数不是静态数据而是会实时更新,传统的命令式UI写法更新界面繁琐且容易同步错误。Compose会对界面用到的数据自动进行订阅(属性委托),当数据变化时界面会自动更新(同为数据和界面关联,databinding只能更新组件的值,Compose可以控制组件切换显示)。
| 声明式UI | 只需要把界面写出来,不需要再手动写代码去刷新界面。重新生成整个屏幕界面成本高昂,Compose生成界面后,数据变动只执行必要的重组(局部刷新)。 |
| 命令式UI | xml写的界面,当数据变了就需要Java/Kotlin手动(命令指挥)刷新,即 findViewById( ) 遍历树拿到控件,再 setText( ) 设置数据改变节点。 |
二、使用
2.1 添加依赖
BoM物料清单:随着依赖的库越来越多,为了保证不同库不同版本之间能正常配合,引入依赖时具体的库不指定版本,而是由BoM管理。
最低版本:Kotlin ≥ 1.5.10、Android ≥ 5.0(API21)、AndroidStudio ≥ Arctic Fox 2020.3.1。
android {
buildFeatures {
compose true //启用Compose功能
}
composeOptions {
//见上方链接,此处定义的Kotlin编译器扩展版本需要对应兼容的Kotlin版本
kotlinCompilerExtensionVersion = "1.4.2"
}
}
dependencies {
//Compose
def composeBom = platform('androidx.compose:compose-bom:2025.12.00')
implementation composeBom
androidTestImplementation composeBom
//主题
implementation 'androidx.compose.material3:material3'
//预览
implementation 'androidx.compose.ui:ui-tooling-preview'
debugImplementation 'androidx.compose.ui:ui-tooling'
//UI测试
androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
debugImplementation 'androidx.compose.ui:ui-test-manifest'
//可选搭配
implementation 'androidx.activity:activity-compose:1.7.0' //Activity
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1' //ViewModel
implementation 'androidx.compose.runtime:runtime-livedata' //LiveData
implementation 'androidx.constraintlayout:constraintlayout-compose:1.0.1' //ConstraintLayout
implementation 'io.coil-kt:coil-compose:2.3.0' //Coil
implementation 'androidx.navigation:navigation-compose:2.5.3' //Navigation
// implementation "com.google.accompanist:accompanist-appcompat-theme:0.28.0" //AppCompatTheme
}
2.2 Activity调用
需要继承的是ComponentActivity,使用 setContent { } 替换 setContentView( )。
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { // 设置显示内容,用来替换setContentView
Show("Hello World!")
}
}
}
本文介绍了AndroidCompose框架,强调其优点如性能提升、声明式UI的自动数据绑定和高效更新。讲解了如何添加Compose依赖,以及在Activity中集成和预览Compose组件的方法,包括处理ViewModel和Android运行时类的预览问题。
1770

被折叠的 条评论
为什么被折叠?



