Android中Compose常用组件以及布局使用方法
一、基础控件详解
1. Text - 文本控件
Text(text = "Hello Compose", // 必填,显示文本color = Color.Blue, // 文字颜色fontSize = 24.sp, // 字体大小(注意使用.sp单位)fontStyle = FontStyle.Italic, // 字体样式(斜体)fontWeight = FontWeight.Bold, // 字体粗细modifier = Modifier.padding(16.dp) // 内边距.background(Color.LightGray) // 背景色
)
核心参数说明:
-
text
:显示的文字内容(必填) -
color
:文字颜色(Color.Red
,Color(0xFF6200EE)
等) -
fontSize
:字体大小(必须使用.sp
单位,如18.sp
) -
fontWeight
:字体粗细(FontWeight.Normal
,Bold
,W800
等) -
modifier
:通用修饰符(设置边距、背景、点击事件等) -
maxLines
:最大行数(超出显示省略号) -
textDecoration
:文本装饰(TextDecoration.Underline
下划线)
效果(示意图):
[浅灰色背景]Hello Compose(蓝色,24sp,粗体,斜体)
2. Button - 按钮控件
val context = LocalContext.currentButton(onClick = { // 必填,点击回调Toast.makeText(context, "Clicked!", Toast.LENGTH_SHORT).show()},colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red, // 按钮背景contentColor = Color.White // 内容颜色),modifier = Modifier.padding(8.dp),enabled = true // 是否启用
) {Icon( // 图标imageVector = Icons.Filled.Favorite,contentDescription = "Like")Spacer(Modifier.width(8.dp)) // 间距Text("Like") // 按钮文字
}
核心参数说明:
-
onClick
:点击事件回调(必填) -
colors
:颜色配置(背景色、文字色) -
enabled
:是否启用(false时变灰色) -
content
:按钮内容(可包含任意Composable)
效果:
[红色按钮] ♥ Like(白色文字)
点击后弹出Toast
3. TextField - 输入框控件
var text by remember { mutableStateOf("") } // 关键:状态管理TextField(value = text, // 当前值(绑定状态)onValueChange = { newText -> // 输入变化回调text = newText },label = { Text("Username") }, // 浮动标签placeholder = { Text("Enter your name") }, // 提示文字leadingIcon = { // 前缀图标Icon(Icons.Filled.Person, null) },keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, // 键盘类型imeAction = ImeAction.Done // 键盘动作),modifier = Modifier.fillMaxWidth()
)
核心参数说明:
-
value
/onValueChange
:必须配合状态管理(remember+mutableStateOf
) -
label
:浮动标签(输入时上浮) -
placeholder
:提示文本(未输入时显示) -
keyboardOptions
:键盘配置(邮箱/数字键盘等) -
singleLine
:是否单行(true时禁用换行)
4. Image - 图片控件
// 加载本地资源
Image(painter = painterResource(R.drawable.dog),contentDescription = "Cute dog", // 必填(无障碍)modifier = Modifier.size(120.dp).clip(CircleShape), // 圆形裁剪contentScale = ContentScale.Crop // 裁剪模式
)// 加载网络图片(Coil)
AsyncImage(model = "https://example.com/image.jpg",contentDescription = "Network image",placeholder = { // 加载中显示CircularProgressIndicator()},error = { // 错误显示Icon(Icons.Filled.Error, null)}
)
核心参数说明:
-
painter
:本地资源(painterResource()
) -
contentDescription
:必填(无障碍支持) -
contentScale
:缩放模式(Crop
,Fit
,Inside
等) -
alpha
:透明度(0.0f-1.0f) -
colorFilter
:颜色滤镜(如黑白效果)
5. ProgressIndicator - 进度指示器
// 圆形进度条
CircularProgressIndicator(progress = 0.7f, // 进度值(0-1)color = Color.Green,strokeWidth = 8.dp,modifier = Modifier.size(50.dp)
)// 线性进度条
LinearProgressIndicator(progress = 0.4f,backgroundColor = Color.LightGray,color = MaterialTheme.colors.primary,modifier = Modifier.fillMaxWidth().padding(16.dp)
)
参数说明:
-
progress
:进度值(0-1),不传则为不确定进度 -
color
:进度条颜色 -
strokeWidth
:圆形进度条粗细 -
backgroundColor
:线性进度条背景色
二、核心布局详解(附结构图)
1. Column - 垂直布局
Column(modifier = Modifier.fillMaxSize() // 占满父布局.background(Color.LightGray),horizontalAlignment = Alignment.CenterHorizontally, // 水平居中verticalArrangement = Arrangement.SpaceEvenly // 等间距分布
) {Text("Item 1")Button(onClick = {}) { Text("Button") }Image(painterResource(R.drawable.icon), null)
}
参数说明:
参数 | 说明 | 常用值 |
---|---|---|
horizontalAlignment | 子项水平对齐 | Start , CenterHorizontally , End |
verticalArrangement | 垂直分布方式 | Top , Center , SpaceBetween , SpaceEvenly |
modifier | 修饰符 | 设置尺寸/背景/边距等 |
布局效果:
┌───────────────────────────┐
│ │
│ Item 1 │
│ │
│ [ Button ] │
│ │
│ [图标] │
│ │
└───────────────────────────┘
(等间距分布)
2. Row - 水平布局
Row(modifier = Modifier.fillMaxWidth().background(Color.LightGray).padding(16.dp).horizontalScroll(rememberScrollState()), // 水平滚动verticalAlignment = Alignment.CenterVertically, // 垂直居中horizontalArrangement = Arrangement.SpaceBetween // 两端对齐
) {Icon(Icons.Filled.Menu, "Menu")Text("Title", fontWeight = FontWeight.Bold)Icon(Icons.Filled.Search, "Search")
}
参数说明:
参数 | 说明 | 常用值 |
---|---|---|
verticalAlignment | 子项垂直对齐 | Top , CenterVertically , Bottom |
horizontalArrangement | 水平分布方式 | Start , Center , SpaceBetween , SpaceAround |
.horizontalScroll() | 水平滚动支持 | 必须添加 |
布局效果:
┌─[菜单]─────标题─────[搜索]─┐
(两端对齐,可横向滚动)
3. Box - 层叠布局
Box(modifier = Modifier.size(200.dp).background(Color.Blue)
) {Image( // 底层painter = painterResource(R.drawable.bg),contentDescription = "Background",modifier = Modifier.fillMaxSize())Text( // 中层"Overlay Text",color = Color.White,modifier = Modifier.align(Alignment.Center).padding(8.dp))Button( // 顶层onClick = {},modifier = Modifier.align(Alignment.BottomEnd).padding(16.dp)) {Text("Action")}
}
关键方法:
-
Modifier.align()
:在Box内定位-
Alignment.TopStart
-
Alignment.Center
-
Alignment.BottomEnd
-
-
Modifier.zIndex()
:控制层级(默认后添加的在上层)
布局效果:
┌───────────────────────────┐
│ [背景图片] │
│ │
│ 居中文字 │
│ │
│ [按钮] │
└───────────────────────────┘
(三层叠加)
三、常见问题
Q1:Compose 为什么需要状态管理?TextField 如何处理状态变化?
答:
// 状态声明
var text by remember { mutableStateOf("") }// 状态绑定
TextField(value = text, // 绑定状态值onValueChange = { newText -> text = newText // 更新状态}
)/*
1. 初始状态 text = ""
2. 用户输入 "A" -> 触发 onValueChange
3. text 更新为 "A"
4. 状态变化触发重组(Recomposition)
5. TextField 根据新值刷新界面
*/
Q2:如何实现列表滚动?
垂直滚动:
Column(modifier = Modifier.verticalScroll(rememberScrollState())
) { /* 长内容 */ }
高性能列表(LazyColumn):
LazyColumn {item { Header() }items(100) { index -> // 只渲染可见项ListItem(index)}item { Footer() }
}
Q3:Box 布局如何实现复杂定位?
Box(modifier = Modifier.fillMaxSize()) {// 左上角Text("TopStart", Modifier.align(Alignment.TopStart))// 右上角Button(onClick = {}, Modifier.align(Alignment.TopEnd)) { ... }// 正中央Image(..., Modifier.align(Alignment.Center))// 左下角Icon(..., Modifier.align(Alignment.BottomStart))// 右下角CircularProgressIndicator(Modifier.align(Alignment.BottomEnd))
}
Q4:如何实现响应式布局?
@Composable
fun AdaptiveLayout() {// 根据屏幕宽度选择布局val configuration = LocalConfiguration.currentval screenWidth = configuration.screenWidthDp.dpif (screenWidth < 600.dp) {VerticalLayout() // 小屏:垂直布局} else {HorizontalLayout() // 大屏:水平布局}
}