我们设置了Box的组件的最小宽高为40dp,但此Box的宽高实际设置成了20dp,如果没有加上这个方法wrapContentSize,那么最终渲染出的Box宽高其实是40dp x 40dp,且是蓝色背景
而由于我们加上了这个方法,最终渲染出的Box宽高就为20dp x 20dp,且排列对齐方式会按照wrapContentSize中的align参数进行
同理,也有单独设置宽度或高度的方法
val interactionSource = remember { MutableInteractionSource() }
Column {
Text(
text = "Click me and my neighbour will indicate as well!",
modifier = Modifier
// clickable will dispatch events using MutableInteractionSource and show ripple
.clickable(
interactionSource = interactionSource,
indication = rememberRipple()
) {
/**do something */
}
.padding(10.dp)
)
Spacer(Modifier.requiredHeight(10.dp))
Text(
text = "I'm neighbour and I indicate when you click the other one",
modifier = Modifier
// this element doesn't have a click, but will show default indication from the
// CompositionLocal as it accepts the same MutableInteractionSource
.indication(interactionSource, LocalIndication.current)
.padding(10.dp)
)
}
// actual composable state that we will show on UI and update in `Scrollable`
val offset = remember { mutableStateOf(0f) }
Box(
Modifier
.size(150.dp)
.scrollable(
orientation = Orientation.Vertical,
// state for Scrollable, describes how consume scroll amount
state = rememberScrollableState { delta ->
offset.value = offset.value + delta // update the state
delta // indicate that we consumed all the pixels available
}
)
.background(Color.LightGray),
contentAlignment = Alignment.Center
) {
Text(offset.value.roundToInt().toString(), style = TextStyle(fontSize = 32.sp))
}
效果
选择 selectable
可用来实现单选功能
val option1 = Color.Red
val option2 = Color.Blue
var selectedOption by remember { mutableStateOf(option1) }
Column {
Text("Selected: $selectedOption")
Row {
listOf(option1, option2).forEach { color ->
val selected = selectedOption == color
Box(
Modifier
.size(100.dp)
.background(color = color)
.selectable(
selected = selected,
onClick = { selectedOption = color }
)
){
if(selected) Text(text = "已选",color = Color.White)
}
}
}
}
效果:
toggleable
类似复选框的勾选及不勾选
var checked by remember { mutableStateOf(false) }
// content that you want to make toggleable
Text(
modifier = Modifier.toggleable(value = checked, onValueChange = { checked = it }),
text = checked.toString()
)