Jetpack Compose ChipGroup
Compose 版本:1.0.0-beta08
效果
添加依赖
...
//流式布局
val accompanistVersion = "0.11.1"
implementation("com.google.accompanist:accompanist-flowlayout:$accompanistVersion")
...
主要代码
/**
* ChipGroup
*
* @param items 数据列表
* @param selectIndex 选择位置状态
*/
@Composable
fun ChipGroup(
items: List<ChipData>,
selectIndex: MutableState<Int>,
modifier: Modifier = Modifier
) {
FlowRow(modifier = modifier) {
items.forEachIndexed { index, chipData ->
ChipItem(item = chipData, selectIndex)
}
}
}
/**
* ChipItem
*/
@Composable
fun ChipItem(item: ChipData, selectIndex: MutableState<Int>) {
val context = LocalContext.current
//背景色
val backgroundColor = if (selectIndex.value == item.index)
colorResource(id = R.color.purple_500)
else
colorResource(id = R.color.white)
//字体颜色
val textColor = if (selectIndex.value == item.index)
MaterialTheme.colors.background
else
MaterialTheme.colors.onBackground
Box(
modifier = Modifier
.padding(6.dp)
.clip(CircleShape)
.background(backgroundColor, CircleShape)
.clickable {
selectIndex.value = item.index
}
) {
Text(
text = item.text,
color = textColor,
style = MaterialTheme.typography.subtitle1,
modifier = Modifier.padding(6.dp)
)
}
}
使用示例
Surface(color = Color.Gray, modifier = Modifier.fillMaxSize()) {
val chipData = arrayListOf(
ChipData(0, "Chip 1"),
ChipData(1, "Chip 2"),
ChipData(2, "Chip 3"),
ChipData(3, "Chip 4"),
ChipData(4, "Chip 5"),
ChipData(5, "Chip 6"),
)
val indexState = remember {
mutableStateOf(0)
}
Column {
Text(text = "已选择:${chipData[indexState.value].text}")
ChipGroup(chipData, indexState)
}
}