我正在使用 Jetpack Compose 在 Kotlin 中编写一个界面。我刚刚学习,按钮布局有问题。
我想让“检查”和“删除”按钮位于输入字段的后面。看一下屏幕截图,它现在的样子以及我正在尝试如何做到这一点。
代码:
Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(text = "Players", style = Typography.titleLarge)
IconButton(onClick = { isNewPlayer = true }) {
Icon(imageVector = Icons.Default.Add, contentDescription = "")
}
}
if (isNewPlayer) {
EditTextFieldSmall(
label = "New Player",
value = newPlayer.toStringWithEmpty(),
onValueChange = { newPlayer = it.toIntWithEmpty() }
)
IconButton(
onClick = {
val newList = club.player.toMutableList()
newList.add(newPlayer)
club = club.copy(player = newList)
newPlayer = 0
isNewPlayer = false
}
) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = "",
tint = Color.Green,
modifier = Modifier.size(16.dp)
)
}
IconButton(
onClick = {
newPlayer = 0
isNewPlayer = false
}
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "",
tint = Color.Red,
modifier = Modifier.size(16.dp)
)
}
}
for (i in club.player.indices) {
EditTextFieldSmall(
label = "Player",
value = club.player[i].toStringWithEmpty(),
onValueChange = {
val newList = club.player.toMutableList()
newList[i] = it.toIntWithEmpty()
club = club.copy(player = newList)
}
)
IconButton(
onClick = {
val newList = club.player.toMutableList()
newList.removeAt(i)
club = club.copy(player = newList)
}
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "",
tint = Color.Red,
modifier = Modifier.size(16.dp)
)
}
}
并且:
@Composable
fun EditTextFieldSmall(label: String, value: String, onValueChange: (String) -> Unit) {
Row(Modifier.fillMaxWidth().padding(top = 4.dp)) {
Text(text = label, color = Color.White)
Spacer(modifier = Modifier.width(8.dp))
BasicTextField(
modifier =
Modifier.width(130.dp)
.height(24.dp)
.background(EditTextFieldBackground, shapes.extraSmall),
value = value,
onValueChange = { newValue ->
if (newValue.length <= 6) {
onValueChange(newValue)
}
},
textStyle =
LocalTextStyle.current.copy(
color = EditTextFieldTextColor,
textAlign = TextAlign.Center
),
keyboardOptions =
KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Done)
)
}
}
上面的截图就是现在的样子:
// 图片
底部屏幕 - 我想要的样子
尝试在 BasicTextField 之前添加行和列
请尝试使用额外的
Row
来包装这三个可组合项的所有出现,如下所示:
Row {
EditTextFieldSmall(
//...
)
IconButton(
//...
) {
//...
}
IconButton(
//...
) {
//...
}
}
此外,从
fillMaxWidth()
可组合项内部的 Row
中删除 EditTextFieldSmall
修饰符:
@Composable
fun EditTextFieldSmall(label: String, value: String, onValueChange: (String) -> Unit) {
Row(Modifier.padding(top = 4.dp)) {
//...
}
}