阅读前请点击右上角“关注”,每天免费获取Android知识解析及面试解答。Android架构解析,只做职场干货,完全免费分享!
Jetpack Compose是什么?
Jetpack Compose 是安卓用于构建UI的一种新方式,采用代码而非xml文件方式,写法与Flutter非常相似。官方主页:https://developer.android.google.cn/jetpack/compose官方Demo:https://github.com/android/compose-samples/tree/master/JetNews官方入门指导: https://developer.android.google.cn/jetpack/compose/tutorial
约束条件Android Studio: 4.0及以上支持安卓版本:Android API 21(即5.0)及以上必须使用kotlin语言优点代码更少少了xml,少了activity和xml之间的关联.双向绑定数据变化了,UI就自动变化.缺点含有参数的Composable函数不能直接预览.Composable函数必须添加@Preview注解才能预览.代码修改后,需要重新编译才能预览.目前还不完善,相比于Flutter,还处于幼儿园水平.相比于xml画页面布局,效率会有降低.常见控件使用样例1. 文本显示Text(text = "众鸟高飞尽,孤云独去闲。相看两不厌,只有敬亭山。")
2. 文本输入框val state = +state { "Text Field to input" }TextField( value = state.value, onValueChange = { state.value = it })
3. 按钮Button(text = "咬我啊", onClick = { Log.v("test", "被咬了") })
4.弹出框MaterialTheme { Column { val openDialog = +state { false } Button("Click me", onClick = { openDialog.value = true }) if (openDialog.value) { AlertDialog( onCloseRequest = { openDialog.value = false }, title = { Text(text = "Alert Dialog Title") }, text = { Text("Alert Dialog content") }, confirmButton = { Button( "Confirm", onClick = { openDialog.value = false }) }, dismissButton = { Button( "Cancel", onClick = { openDialog.value = false }) }, buttonLayout = AlertDialogButtonLayout.Stacked ) } }}
5. 开关MaterialTheme { val checkedState = +state { true } Switch( checked = checkedState.value, onCheckedChange = { checkedState.value = it } )}
6. 单选框MaterialTheme { RadioButton(selected = true, onSelect = { } )}
7. 复选框MaterialTheme { val checkedState = +state { true } Checkbox( checked = checkedState.value, onCheckedChange = { checkedState.value = it } )}
8. 单选框组MaterialTheme { val radioOptions = listOf("A", "B", "C") val (selectedOption, onOptionSelected) = +state { radioOptions[0] } RadioGroup( options = radioOptions, selectedOption = selectedOption, onSelectedChange = onOptionSelected )}
9.图片Container(modifier = Height(300.dp) wraps Expanded) { Clip(shape = RoundedCornerShape(4.dp)) { DrawImage(+imageResource(R.drawable.img_0)) }}
源代码
https://github.com/cxyzy1/Jetpack-Compose-Demos
作者:程序园中猿