Jetpack Compose 属性配置
使用的 Jetpack Compose 属性配置,包括尺寸、布局、样式、动画等各个方面。
目录
1. 尺寸与布局属性
1.1 fillMaxSize
描述:让组件填充父容器的全部可用空间。
语法:
Modifier.fillMaxSize(fraction: Float = 1f)
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| fraction | Float | 1f | 填充比例,0.0-1.0 之间 |
使用示例:
Box(
modifier = Modifier
// 填充整个父容器
.fillMaxSize()
)
Box(
modifier = Modifier
// 填充父容器的 50%
.fillMaxSize(0.5f)
)
注意事项:
- 必须在有约束的父容器中使用
- 与
wrapContentSize互斥
1.2 fillMaxWidth
描述:让组件填充父容器的全部可用宽度。
语法:
Modifier.fillMaxWidth(fraction: Float = 1f)
使用示例:
Column(
modifier = Modifier
// 填充父容器宽度
.fillMaxWidth()
)
Box(
modifier = Modifier
// 填充父容器宽度的 80%
.fillMaxWidth(0.8f)
)
1.3 fillMaxHeight
描述:让组件填充父容器的全部可用高度。
语法:
Modifier.fillMaxHeight(fraction: Float = 1f)
使用示例:
Row(
modifier = Modifier
// 填充父容器高度
.fillMaxHeight()
)
1.4 width / height
描述:设置组件的固定宽度或高度。
语法:
Modifier.width(width: Dp)
Modifier.height(height: Dp)
Modifier.size(size: Dp) // 同时设置宽高
Modifier.size(width: Dp, height: Dp) // 分别设置宽高
使用示例(实际用法):
// 使用自定义扩展函数 px() 进行屏幕适配
Image(
modifier = Modifier
// 设置宽度为 390 像素(已适配屏幕)
.width(390.px())
// 设置高度为 390 像素
.height(390.px())
)
// 同时设置宽高
Box(
modifier = Modifier
// 设置尺寸为 58x58 像素
.size(58.px())
)
// 分别设置宽高
Image(
modifier = Modifier
.width(44.px())
.height(38.px())
)
最佳实践:
- 建议使用响应式尺寸而非硬编码
- 使用提供的
px()扩展函数进行屏幕适配
1.5 wrapContentSize
描述:让组件包裹其内容,只占用必要的空间。
语法:
Modifier.wrapContentSize(
align: Alignment = Alignment.Center,
unbounded: Boolean = false
)
使用示例:
Text(
text = "Hello",
modifier = Modifier
// 只占用文本所需空间
.wrapContentSize()
)
2. 对齐与定位属性
2.1 align
描述:在父容器中设置子组件的对齐方式。
语法:
// 用于 BoxScope 中的子组件
Modifier.align(alignment: Alignment)
可选值:
| 对齐方式 | 说明 |
|---|---|
Alignment.TopStart | 左上角 |
Alignment.TopCenter | 顶部居中 |
Alignment.TopEnd | 右上角 |
Alignment.CenterStart | 左侧居中 |
Alignment.Center | 正中心 |
Alignment.CenterEnd | 右侧居中 |
Alignment.BottomStart | 左下角 |
Alignment.BottomCenter | 底部居中 |
Alignment.BottomEnd | 右下角 |
使用示例(实际用法):
@Composable
fun BoxScope.BottomBar() {
Box(
Modifier
// 在父容器中底部居中对齐
.align(Alignment.BottomCenter)
)
}
@Composable
fun BoxScope.WeatherInfo() {
Column(
modifier = Modifier
// 在父容器中顶部居中对齐
.align(Alignment.TopCenter)
)
}
注意事项:
- 只能在
Box容器的子组件中使用(需要BoxScope) - 每个子组件只能设置一个对齐位置
2.2 contentAlignment
描述:设置容器内所有子组件的默认对齐方式。
语法:
Box(
contentAlignment: Alignment = Alignment.TopStart
) { }
使用示例:
Box(
modifier = Modifier.fillMaxSize(),
// 所有子组件默认居中对齐
contentAlignment = Alignment.Center
) {
Text("Centered Text")
}
2.3 horizontalAlignment / verticalArrangement
描述:设置 Column 和 Row 中子组件的对齐方式。
Column 专用:
Column(
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
verticalArrangement: Arrangement.Vertical = Arrangement.Top
) { }
Row 专用:
Row(
horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
verticalAlignment: Alignment.Vertical = Alignment.Top
) { }
使用示例(实际用法):
Column(
modifier = Modifier.fillMaxWidth(),
// 子元素水平居中对齐
horizontalAlignment = Alignment.CenterHorizontally,
// 子元素之间垂直间隔 12 像素
verticalArrangement = Arrangement.spacedBy(12.px())
) { }
Row(
modifier = Modifier.fillMaxWidth(),
// 子元素均匀分布在行内
horizontalArrangement = Arrangement.SpaceAround
) { }
Arrangement 可选值:
| 值 | 说明 |
|---|---|
Arrangement.Start | 从起始位置排列 |
Arrangement.End | 从结束位置排列 |
Arrangement.Center | 居中对齐 |
Arrangement.SpaceEvenly | 均匀分布,包括首尾 |
Arrangement.SpaceBetween | 均匀分布,首尾无间距 |
Arrangement.SpaceAround | 均匀分布,首尾间距为一半 |
Arrangement.spacedBy(Dp) | 指定间距 |
3. 背景与填充属性
3.1 background
描述:设置组件的背景颜色或渐变。
语法:
// 纯色背景
Modifier.background(
color: Color,
shape: Shape = RectangleShape
)
// 渐变背景
Modifier.background(
brush: Brush,
shape: Shape = RectangleShape,
alpha: Float = 1.0f
)
使用示例(实际用法):
// 纯色半透明背景
Box(
modifier = Modifier
.background(Color.Black.copy(0.3f))
)
// 水平渐变背景
Box(
modifier = Modifier
.background(
brush = Brush.horizontalGradient(
colors = listOf(
Color(0xFF3A3A6A), // 渐变起始颜色
Color(0xFF25244C), // 渐变结束颜色
)
)
)
)
// 线性渐变背景
Box(
modifier = Modifier
.background(
brush = Brush.linearGradient(
colors = listOf(
Color.Transparent,
Color.White.copy(0.76f)
)
)
)
)
Brush 类型:
| 类型 | 说明 |
|---|---|
Brush.horizontalGradient | 水平方向渐变 |
Brush.verticalGradient | 垂直方向渐变 |
Brush.linearGradient | 线性渐变(可指定角度) |
Brush.radialGradient | 径向渐变 |
Brush.sweepGradient | 扫描渐变 |
带色标的渐变:
.background(
brush = Brush.horizontalGradient(
// 指定颜色在渐变中的位置(0.0f - 1.0f)
0.06f to Color.Transparent,
0.28f to Color.White,
0.47f to Color.Transparent
)
)
3.2 paint
描述:使用 Painter 绘制组件背景,主要用于设置图片背景。
语法:
Modifier.paint(
painter: Painter,
contentScale: ContentScale = ContentScale.Inside,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null
)
使用示例(实际用法):
Box(
modifier = Modifier
.fillMaxSize()
// 设置背景图片
.paint(
painter = painterResource(R.mipmap.bg),
// 图片裁剪模式:按比例裁剪填满容器
contentScale = ContentScale.Crop
)
)
ContentScale 可选值:
| 值 | 说明 |
|---|---|
ContentScale.Fit | 保持比例,完整显示 |
ContentScale.Crop | 保持比例,裁剪填满 |
ContentScale.FillBounds | 拉伸填满,可能变形 |
ContentScale.FillWidth | 宽度填满,高度自适应 |
ContentScale.FillHeight | 高度填满,宽度自适应 |
ContentScale.Inside | 在边界内完整显示 |
ContentScale.None | 不缩放 |
background vs paint 对比:
| 特性 | background | paint |
|---|---|---|
| 用途 | 颜色/渐变 | 图片/位图 |
| 性能 | 轻量 | 较重 |
| 适用 | 简单背景 | 复杂图像 |
4. 边框与形状属性
4.1 border
描述:为组件添加边框。
语法:
// 纯色边框
Modifier.border(
width: Dp,
color: Color,
shape: Shape = RectangleShape
)
// 渐变边框
Modifier.border(
width: Dp,
brush: Brush,
shape: Shape = RectangleShape
)
使用示例(实际用法):
// 纯色半透明边框
Box(
modifier = Modifier
.border(
width = 1.px(),
color = Color(0xFF7582F4).copy(0.5f),
shape = TopWaveBarShape
)
)
// 渐变边框
Box(
modifier = Modifier
.border(
width = 1.px(),
brush = Brush.linearGradient(
colors = listOf(
Color.White,
Color(0xFFAEAEAE)
)
),
shape = CircleShape
)
)
4.2 clip
描述:将组件裁剪为指定形状。
语法:
Modifier.clip(shape: Shape)
使用示例(实际用法):
// 裁剪为圆形
Box(
modifier = Modifier
.clip(CircleShape)
)
// 裁剪为自定义波浪形状
Box(
modifier = Modifier
.clip(TopWaveBarShape)
)
// 裁剪为自定义弧形形状
Box(
modifier = Modifier
.clip(CurvedTopShape)
)
内置形状:
| 形状 | 说明 |
|---|---|
RectangleShape | 矩形 |
CircleShape | 圆形 |
RoundedCornerShape(Dp) | 圆角矩形 |
自定义形状:
// 在 CustomShape.kt 中定义
val TopWaveBarShape = GenericShape { size, _ ->
// 使用贝塞尔曲线定义形状路径
val w = size.width
val h = size.height
// ... 路径定义
}
5. 阴影与效果属性
5.1 dropShadow
描述:为组件添加外部阴影效果(新拟态设计常用)。
语法:
Modifier.dropShadow(
shape: Shape,
shadow: Shadow
)
Shadow 参数:
| 参数 | 类型 | 说明 |
|---|---|---|
| radius | Dp | 阴影模糊半径 |
| color | Color | 阴影颜色 |
| offset | DpOffset | 阴影偏移量 |
使用示例(实际用法):
Box(
modifier = Modifier
// 左上白色投影(新拟态效果)
.dropShadow(
shape = CircleShape,
shadow = Shadow(
radius = 20.px(),
color = Color.White.copy(0.5f),
offset = DpOffset((-10).px(), (-10).px())
)
)
// 右下深色投影(新拟态效果)
.dropShadow(
shape = CircleShape,
shadow = Shadow(
radius = 20.px(),
color = Color(0xFF0D1431).copy(0.5f),
offset = DpOffset((10).px(), (10).px())
)
)
)
注意事项:
- 需要导入
androidx.compose.ui.graphics.shadow.Shadow - 可叠加多个阴影实现复杂效果
- 阴影方向通过 offset 控制
5.2 innerShadow
描述:为组件添加内部阴影效果。
语法:
Modifier.innerShadow(
shape: Shape,
shadow: Shadow
)
使用示例(实际用法):
Box(
modifier = Modifier
.innerShadow(
shape = CircleShape,
shadow = Shadow(
radius = (0.5f).px(),
color = Color.White,
offset = DpOffset((1).px(), (1).px())
)
)
)
6. 内边距与外边距属性
6.1 padding
描述:为组件添加内边距。
语法:
// 统一内边距
Modifier.padding(all: Dp)
// 水平/垂直内边距
Modifier.padding(horizontal: Dp, vertical: Dp)
// 分别设置四边
Modifier.padding(start: Dp, top: Dp, end: Dp, bottom: Dp)
// 单独设置某一边
Modifier.padding(start: Dp)
Modifier.padding(top: Dp)
Modifier.padding(end: Dp)
Modifier.padding(bottom: Dp)
使用示例(实际用法):
// 顶部内边距
Image(
modifier = Modifier
.padding(top = 334.px())
)
// 垂直和水平内边距
Column(
modifier = Modifier
.padding(vertical = 16.px(), horizontal = 8.px())
)
// 统一内边距
Box(
modifier = Modifier
.padding(16.px())
)
最佳实践:
- 使用
padding而非margin(Compose 没有 margin 概念) - 建议按照
top→horizontal→bottom的顺序设置
6.2 offset
描述:相对于原始位置偏移组件。
语法:
Modifier.offset(x: Dp, y: Dp)
Modifier.offset(offset: DpOffset)
使用示例:
Box(
modifier = Modifier
.offset(x = 10.px(), y = 20.px())
)
注意事项:
- 偏移不会影响布局测量
- 仅改变绘制位置
7. 文本样式属性
7.1 fontSize
描述:设置文本字体大小。
语法:
Text(
fontSize: TextUnit
)
使用示例(实际用法):
// 使用自定义扩展函数 textPx() 进行屏幕适配
Text(
text = "Montreal",
fontSize = 34.textPx()
)
Text(
text = "19°",
fontSize = 96.textPx()
)
7.2 fontWeight
描述:设置文本字体粗细。
语法:
Text(
fontWeight: FontWeight
)
可选值:
| 值 | 说明 |
|---|---|
FontWeight.Thin | 极细 (100) |
FontWeight.ExtraLight | 特细 (200) |
FontWeight.Light | 细体 (300) |
FontWeight.Normal | 常规 (400) |
FontWeight.Medium | 中等 (500) |
FontWeight.SemiBold | 半粗 (600) |
FontWeight.Bold | 粗体 (700) |
FontWeight.ExtraBold | 特粗 (800) |
FontWeight.Black | 黑体 (900) |
使用示例(实际用法):
Text(
text = "19°",
fontWeight = FontWeight.Thin // 极细字体
)
Text(
text = "Hourly Forecast",
fontWeight = FontWeight.SemiBold // 半粗体
)
7.3 color
描述:设置文本颜色。
语法:
Text(
color: Color
)
使用示例(实际用法):
// 纯白色
Text(
color = Color.White
)
// 带透明度的颜色
Text(
color = Color(0xFFEBEBF5).copy(0.6f)
)
7.4 textAlign
描述:设置文本对齐方式。
语法:
Text(
textAlign: TextAlign
)
可选值:
| 值 | 说明 |
|---|---|
TextAlign.Start | 起始对齐 |
TextAlign.End | 结束对齐 |
TextAlign.Center | 居中对齐 |
TextAlign.Left | 左对齐 |
TextAlign.Right | 右对齐 |
TextAlign.Justify | 两端对齐 |
使用示例(实际用法):
Text(
text = buildAnnotatedString { ... },
textAlign = TextAlign.Center // 居中对齐
)
7.5 buildAnnotatedString
描述:构建富文本,支持多种样式。
语法:
Text(
text = buildAnnotatedString {
// 文本构建
}
)
使用示例(实际用法):
Text(
text = buildAnnotatedString {
// 使用样式:设置天气描述文本颜色
withStyle(
style = SpanStyle(
color = Color(0xFFEBEBF5).copy(0.6f)
)
) {
append("Mostly Clear")
}
// 换行
append("\n")
// 添加最高最低温度
append("H:24° L:18°")
}
)
8. 动画属性
8.1 animateColorAsState
描述:创建颜色动画状态,当目标值改变时自动过渡。
语法:
val animatedColor by animateColorAsState(
targetValue: Color,
animationSpec: AnimationSpec<Color> = defaultColorAnimationSpec,
label: String = "ColorAnimation"
)
使用示例(实际用法):
var currentIndex by remember { mutableIntStateOf(1) }
itemsIndexed(data) { index, item ->
val selected = index == currentIndex
// 使用动画颜色过渡
val animatedColor by animateColorAsState(
// 选中时为深紫色,未选中时为深紫色半透明
targetValue = if (selected) Color(0xFF48319D) else Color(0xFF48319D).copy(0.2f)
)
Box(
modifier = Modifier
.background(color = animatedColor)
)
}
注意事项:
- 使用
by关键字进行委托 - 自动处理动画的生命周期
- 默认使用弹簧动画
9. 其他常用属性
9.1 clickable / combinedClickable
描述:为组件添加点击事件。
语法:
Modifier.clickable(
enabled: Boolean = true,
onClickLabel: String? = null,
role: Role? = null,
onClick: () -> Unit
)
使用示例:
Button(
onClick = { /* 点击处理 */ }
) {
Text("Click Me")
}
// 或给任意组件添加点击
Box(
modifier = Modifier
.clickable { /* 点击处理 */ }
)
9.2 alpha
描述:设置组件透明度。
语法:
Modifier.alpha(alpha: Float)
使用示例:
Image(
modifier = Modifier
.alpha(0.5f) // 50% 透明度
)
9.3 rotate
描述:旋转组件。
语法:
Modifier.rotate(degrees: Float)
使用示例:
Icon(
modifier = Modifier
.rotate(45f) // 旋转 45 度
)
9.4 scale
描述:缩放组件。
语法:
Modifier.scale(scale: Float)
Modifier.scale(scaleX: Float, scaleY: Float)
使用示例:
Image(
modifier = Modifier
.scale(1.5f) // 放大 1.5 倍
)
9.5 zIndex
描述:设置组件的 Z 轴顺序。
语法:
Modifier.zIndex(zIndex: Float)
使用示例:
Box(
modifier = Modifier
.zIndex(1f) // 较高的层级
)
10. 未实现但常用的属性
10.1 weight
描述:在 Row 或 Column 中分配剩余空间的比例。
使用场景:等分布局、自适应宽度/高度
示例:
Row {
// 占据 1/3 宽度
Box(
modifier = Modifier
.weight(1f)
.fillMaxHeight()
)
// 占据 2/3 宽度
Box(
modifier = Modifier
.weight(2f)
.fillMaxHeight()
)
}
10.2 aspectRatio
描述:设置组件的宽高比。
使用场景:图片网格、视频播放器、保持比例的卡片
示例:
Image(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(16f / 9f) // 16:9 比例
)
10.3 graphicsLayer
描述:提供高级图形变换功能。
使用场景:复杂动画、3D 效果、渲染优化
示例:
Box(
modifier = Modifier
.graphicsLayer {
scaleX = 1.2f
scaleY = 1.2f
alpha = 0.8f
rotationZ = 45f
shadowElevation = 10f
}
)
10.4 animateContentSize
描述:在内容大小变化时自动添加动画。
使用场景:展开/收起效果、动态内容
示例:
Column(
modifier = Modifier
.animateContentSize(
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
) {
if (expanded) {
Text("展开的内容")
}
}
10.5 horizontalScroll / verticalScroll
描述:为组件添加滚动功能。
使用场景:横向滚动列表、长文本滚动
示例:
Row(
modifier = Modifier
.horizontalScroll(rememberScrollState())
) {
// 可横向滚动的内容
}
10.6 pointerInput
描述:处理手势输入。
使用场景:自定义手势、拖动、缩放
示例:
Box(
modifier = Modifier
.pointerInput(Unit) {
detectTapGestures(
onTap = { /* 单击 */ },
onDoubleTap = { /* 双击 */ },
onLongPress = { /* 长按 */ }
)
}
)
10.7 draggable / swipeable
描述:添加拖动功能。
使用场景:滑动删除、拖拽排序、抽屉效果
示例:
Box(
modifier = Modifier
.draggable(
state = rememberDraggableState { delta ->
// 处理拖动
},
orientation = Orientation.Horizontal
)
)
10.8 layout
描述:自定义组件的测量和布局逻辑。
使用场景:复杂自定义布局、性能优化
示例:
Box(
modifier = Modifier
.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
placeable.placeRelative(0, 0)
}
}
)
10.9 onGloballyPositioned
描述:获取组件在屏幕中的位置和尺寸。
使用场景:计算相对位置、动态调整布局
示例:
Box(
modifier = Modifier
.onGloballyPositioned { coordinates ->
val position = coordinates.positionInWindow()
val size = coordinates.size
}
)
10.10 bringIntoViewRequester
描述:控制组件滚动到可视区域。
使用场景:表单验证、搜索高亮
示例:
val bringIntoViewRequester = remember { BringIntoViewRequester()()
Box(
modifier = Modifier
.bringIntoViewRequester(bringIntoViewRequester)
)
// 在需要时调用
bringIntoViewRequester.bringIntoView()
最佳实践总结
1. 属性调用顺序
推荐的 Modifier 调用顺序:
Modifier
// 1. 尺寸和约束
.fillMaxSize()
// 2. 内边距
.padding(16.px())
// 3. 背景
.background(Color.White)
// 4. 边框
.border(1.px(), Color.Gray)
// 5. 形状
.clip(RoundedCornerShape(8.px()))
// 6. 阴影
.shadow(4.px())
// 7. 点击事件
.clickable { }