我创建了两个芯片和芯片@Composable函数,我这样使用:
Chips {
Chip(text = "Apple")
Chip(text = "Banana")
Chip(text = "Cherry")
}我希望第一个也是最后一个芯片看起来有点不同。我可以通过对芯片函数使用额外的参数来做到这一点:
Chips {
Chip(text = "Apple", isFirst = true)
Chip(text = "Banana")
Chip(text = "Cherry", isLast = true)
}有点麻烦。我如何让单个芯片意识到它的兄弟姐妹。
类似地,我们可能想要改变芯片的颜色,这取决于里面是否有芯片。
Chips(chipCount = if (addCherry) 3 else 2) {
Chip(text = "Apple")
Chip(text = "Banana")
if (addCherry) Chip(text = "Cherry")
}我该怎么做才能更优雅。
发布于 2022-03-30 14:45:17
我会将芯片数据数组发送到可组合的Chips中,然后使用循环添加Chip可组合性。
@Composable
fun Chips(
chips: List<ChipData>
) {
chips.forEachIndexed { index, chip ->
Chip(
text = chip.text,
isFirst = index == 0,
isLast = index == chips.lastIndex,
)
}
}类似地,您可以根据Chips对象列表的大小更改Chip的颜色。
如果您想要传递多个完全不同的可组合性,那么插槽也可以节省您的精力(这就是工具栏和类似工具条的实现方式)。而不是一个对象,而是发送一个可组合的,然后它可以是您想要的任何东西(同样的Button也已经完成)。以下是其中的一个例子:
@Composable
fun ListOfComposables() {
val comps = listOf<@Composable (isFirst: Boolean, isLast: Boolean) -> Unit>(
{ isFirst, isLast -> Chip(text = "first chip", isFirst = isFirst, isLast = isLast) },
{ isFirst, isLast -> Chip(text = "chip2", isFirst = isFirst, isLast = isLast) },
{ _, _ ->
Button(onClick = { }) {
Text(text = "Button")
}
},
{ isFirst, isLast -> Chip(text = "Chip3", isFirst = isFirst, isLast = isLast) },
{ _, _ -> Text(text = "Random text") },
{ isFirst, isLast -> Chip(text = "last chip", isFirst = isFirst, isLast = isLast) }
)
Column {
comps.forEachIndexed { index, function ->
function(
isFirst = index == 0,
isLast = index == comps.lastIndex
)
}
}
}
@Composable
fun Chip(
text: String,
isFirst: Boolean = false,
isLast: Boolean = false
) {
Text(
text = text,
color = when {
isFirst -> Color.Green
isLast -> Color.Red
else -> Color.Unspecified
},
modifier = Modifier
.background(Color.LightGray),
)
}此代码的预览如下所示:

。
代码很难看,但我希望它能让人明白这一点。
发布于 2022-04-08 06:51:40
我将在Chips可组合中传递列表,但我将在ChipData中添加uiInfo (密封类或枚举),然后在forEach循环中执行一个when。
就像这样:
enum class UIInfo {
FILTER, INVERSE, NORMAL
}
data class ChipData(
val text: String,
val uiInfo: UIInfo,
)
@Composable
fun Chips(
chips: List<ChipData>
) {
chips.forEach { chip ->
Chip(
text = chip.text,
uiInfo = chip.uiInfo,
)
}
}https://stackoverflow.com/questions/71679274
复制相似问题