Jetpack Compose 是一款全新的 Android UI 工具包,它采用了声明式编程模型,可以让开发者更加高效地构建漂亮的用户界面。Jetpack Compose 还提供了一系列的组件和布局,可以帮助开发者快速构建复杂的 UI 界面。同时,Jetpack Compose 还支持动态主题、动画效果、手势交互等功能,可以让应用程序更加生动、丰富。总之,Jetpack Compose 是一款非常有前途的 Android UI 工具包,值得开发者们深入学习和使用。
效果图:
代码:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
QuadrantTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting()
}
}
}
}
}
@Composable
fun Greeting() {
// Modifier.fillMaxSize() 宽高同时铺满屏幕
Column(Modifier.fillMaxSize()) {
Row(Modifier.weight(1f)) {
Quadrant(
title = stringResource(
id = R.string.first_title),
content = "Displays text and follows Material Design guidelines.",
backgroundColor = Color.Green,
modifier = Modifier.weight(1f)) // weight() 设置权重;
Quadrant(
title = "Image composable",
content = "Displays text and follows Material Design guidelines.",
backgroundColor = Color.Cyan,
modifier = Modifier.weight(1f))
}
Row(Modifier.weight(1f).border(1.dp, Color.Blue)) {
Quadrant(
title = "Row composable",
content = "Displays text and follows Material Design guidelines.",
backgroundColor = Color.Gray,
modifier = Modifier.weight(1f))
Quadrant(
title = "Column composable",
content = "Displays text and follows Material Design guidelines.",
backgroundColor = Color.Magenta,
modifier = Modifier.weight(1f))
}
}
}
@Composable
fun Quadrant(title: String, content: String, backgroundColor: Color, modifier: Modifier = Modifier) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center,
modifier = modifier
.fillMaxSize()
.background(backgroundColor)
.padding(16.dp)) {
Text(text = title, fontWeight = FontWeight.Bold)
Text(text = content, textAlign = TextAlign.Justify)
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
QuadrantTheme {
Greeting()
}
}