有几种解决方案。对于桌面 Compose,偏移图标。对于移动 Compose,调整基线。最后,只需创建一个自定义 TextField。
图标底部可能有额外的填充。也可能是图标和文本始终与顶部对齐。您可以将图标替换为没有底部填充的图标或向上移动图标。您可以看出图标正在影响垂直对齐,因为如果您注释掉您的图标,文本会垂直居中。您也可以尝试减小图标的大小。
在桌面 Compose 上,向上移动图标:
OutlinedTextField(
value = text,
onValueChange = { text = it },
modifier = Modifier.fillMaxWidth(),
leadingIcon = {
Icon(
modifier = Modifier.offset(y = -3.dp),
contentDescription = null,
imageVector = Icons.Default.ArrowForward
)
},
trailingIcon = {
Icon(
modifier = Modifier.offset(y = -3.dp),
contentDescription = null,
imageVector = Icons.Default.ArrowForward
)
})
在移动设备上,您可以调整baseline
文本的:
OutlinedTextField(
value = text,
textStyle = TextStyle(baselineShift = BaselineShift(-0.2f)),
onValueChange = { text = it },
modifier = Modifier.fillMaxWidth(),
leadingIcon = {
Icon(
contentDescription = null,
imageVector = Icons.Default.ArrowForward
)
},
trailingIcon = {
Icon(
contentDescription = null,
imageVector = Icons.Default.ArrowForward
)
})
这里还有一个自定义的 TextField:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CustomTextField(
initialText = "cool",
onValueChange = {
},
onLeftButtonClick = {
},
onRightButtonClick = {
}
)
}
}
}
@Composable
fun CustomTextField(
initialText: String,
onValueChange: (text: String) -> Unit,
onLeftButtonClick: () -> Unit,
onRightButtonClick: () -> Unit
) {
var text by remember { mutableStateOf(initialText) }
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentSize()
.background(color = Color.White, shape = RoundedCornerShape(8.dp))
.border(width = 1.dp, shape = RoundedCornerShape(8.dp), color = Color(0xFF585858))
) {
ConstraintLayout(
modifier = Modifier.fillMaxWidth()
) {
val (left, mid, right) = createRefs()
IconButton(onClick = onLeftButtonClick,
modifier = Modifier.constrainAs(left) {
start.linkTo(parent.start, margin = 10.dp)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}) {
Icon(
contentDescription = null,
imageVector = Icons.Default.ArrowForward,
)
}
IconButton(onClick = onRightButtonClick,
modifier = Modifier.constrainAs(right) {
end.linkTo(parent.end, margin = 10.dp)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}) {
Icon(
contentDescription = null,
imageVector = Icons.Default.ArrowForward,
)
}
TextField(
value = text,
onValueChange = {
text = it
onValueChange(it)
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.White
),
modifier = Modifier
.offset(y = 4.dp)
.constrainAs(mid) {
start.linkTo(left.end, margin = 10.dp)
top.linkTo(parent.top)
end.linkTo(right.start, margin = 10.dp)
bottom.linkTo(parent.bottom)
width = Dimension.fillToConstraints
})
}
}