Compose 基础组件
文本组件
Text 组件
// 基本文本
Text("Hello Compose")
// 样式设置
Text(
text = "Styled Text",
color = Color.Blue,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)TextField 组件
var text by remember { mutableStateOf("") }
TextField(
value = text,
onValueChange = { text = it },
label = { Text("输入框") },
placeholder = { Text("请输入内容") }
)按钮组件
Button 组件
Button(
onClick = { /* 处理点击事件 */ },
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colors.primary
)
) {
Text("点击我")
}IconButton 组件
IconButton(onClick = { /* 处理点击事件 */ }) {
Icon(Icons.Filled.Favorite, contentDescription = "收藏")
}图片组件
Image 组件
Image(
painter = painterResource(id = R.drawable.image),
contentDescription = "示例图片",
modifier = Modifier
.size(100.dp)
.clip(CircleShape)
)AsyncImage 组件
AsyncImage(
model = "https://example.com/image.jpg",
contentDescription = "网络图片",
placeholder = painterResource(R.drawable.loading)
)列表组件
LazyColumn
LazyColumn {
items(items = listOf("Item 1", "Item 2", "Item 3")) { item ->
Text(
text = item,
modifier = Modifier.padding(16.dp)
)
}
}LazyRow
LazyRow {
items(10) { index ->
Card(
modifier = Modifier
.size(100.dp)
.padding(8.dp)
) {
Text("Item $index")
}
}
}容器组件
Card 组件
Card(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
elevation = 4.dp
) {
Column(modifier = Modifier.padding(16.dp)) {
Text("卡片标题", style = MaterialTheme.typography.h6)
Text("卡片内容", style = MaterialTheme.typography.body1)
}
}Surface 组件
Surface(
modifier = Modifier.padding(8.dp),
elevation = 8.dp,
shape = RoundedCornerShape(8.dp)
) {
Text(
text = "Surface 示例",
modifier = Modifier.padding(16.dp)
)
}选择组件
Checkbox 组件
var checked by remember { mutableStateOf(false) }
Checkbox(
checked = checked,
onCheckedChange = { checked = it }
)RadioButton 组件
var selectedOption by remember { mutableStateOf(0) }
val options = listOf("选项1", "选项2", "选项3")
Column {
options.forEachIndexed { index, text ->
Row(
Modifier
.fillMaxWidth()
.selectable(
selected = (selectedOption == index),
onClick = { selectedOption = index }
)
.padding(8.dp)
) {
RadioButton(
selected = (selectedOption == index),
onClick = { selectedOption = index }
)
Text(
text = text,
modifier = Modifier.padding(start = 16.dp)
)
}
}
}最佳实践
-
组件复用
- 抽取常用组件
- 使用参数定制化
- 保持组件单一职责
-
性能优化
- 合理使用 remember
- 避免不必要的重组
- 使用 key 管理列表项
-
无障碍支持
- 提供合适的 contentDescription
- 使用语义化的组件
- 确保足够的点击区域
注意事项
-
状态管理
- 正确使用 remember
- 合理提升状态
- 避免状态泄露
-
组件生命周期
- 理解组件重组机制
- 正确处理副作用
- 及时清理资源
-
主题适配
- 遵循 Material Design
- 支持深色模式
- 响应主题变化