Android Jetpack Compose:使用 FloatingActionButton 或 IconButton 创建漂亮的加减按钮
在 Jetpack Compose 中,可以使用 Material Design 中的 FloatingActionButton 或 IconButton 组件来创建漂亮的加减按钮。下面是一个示例代码,演示了如何使用 FloatingActionButton 和 IconButton 来增加和减少文本框中的数量:
@Composable
fun QuantityCounter() {
var quantity by remember { mutableStateOf(0) }
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = { if (quantity > 0) quantity-- }
) {
Icon(Icons.Filled.Remove, contentDescription = 'Decrease Quantity')
}
Text(
text = quantity.toString(),
modifier = Modifier.padding(horizontal = 16.dp)
)
IconButton(
onClick = { quantity++ }
) {
Icon(Icons.Filled.Add, contentDescription = 'Increase Quantity')
}
}
}
@Preview
@Composable
fun QuantityCounterPreview() {
QuantityCounter()
}
在上述代码中,我们使用 remember { mutableStateOf(0) } 创建了一个名为 quantity 的可变状态,用于存储数量。然后,我们在 Row 中使用了两个 IconButton 组件,一个用于减少数量,一个用于增加数量。在点击这两个按钮时,我们更新 quantity 的值,然后通过 Text 组件显示到屏幕上。
你可以将 QuantityCounter 组件添加到你的 Jetpack Compose UI 中,以实现增加和减少数量的功能。
原文地址: https://www.cveoy.top/t/topic/pkrX 著作权归作者所有。请勿转载和采集!