我遇到了以下问题 - 下拉菜单的项目宽度与 OutlinedTextField 不同。
以下是完整的代码:
寻找解决方案 - 找到了以下内容:
添加变量以保持
textField
的宽度:var textFieldSize by remember { mutableStateOf(Size.Zero) }
在
TextField
的onGloballyPositioned
中设置值:onGloballyPositioned { coordinates -> textFieldSize = coordinates.size.toSize() }
在
ExposedDropdownMenu
中读取该值:ExposedDropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, modifier = Modifier .background(Color.White) .width(with(LocalDensity.current) { textFieldSize.width.toDp() }) )
DropdownMenu
一起使用时运行良好,但与ExposedDropdownMenu
一起使用时不起作用。问题出在哪里?以下是完整的代码:
var expanded by remember { mutableStateOf(false) }
val genderList by remember { mutableStateOf(listOf("Male", "Female")) }
var textFieldSize by remember { mutableStateOf(Size.Zero) }
val icon = if (expanded)
Icons.Filled.ArrowDropUp
else
Icons.Filled.ArrowDropDown
ExposedDropdownMenuBox(
modifier = modifier
.clickable(onClick = { expanded = true }),
expanded = expanded,
onExpandedChange = { expanded = !expanded }
) {
OutlinedTextField(
value = "",
onValueChange = {},
modifier = Modifier
.fillMaxWidth()
.onGloballyPositioned { coordinates ->
textFieldSize = coordinates.size.toSize()
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = BorderColor,
unfocusedIndicatorColor = Color.Transparent,
focusedIndicatorColor = BrandColor,
focusedLabelColor = BrandColor,
),
leadingIcon = {
Image(
painter = painterResource(id = R.drawable.ic_complete_registration_sex),
contentDescription = null
)
},
trailingIcon = { Icon(icon, null) },
shape = RoundedCornerShape(Dimen.Dimen14),
label = {
Text(
"Choose Gender",
style = PoppinsNormalStyle14
)
},
readOnly = true
)
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier
.background(Color.White)
.width(with(LocalDensity.current) { textFieldSize.width.toDp() })
) {
genderList.forEach {
DropdownMenuItem(
onClick = { expanded = false },
) {
Text(it, style = PoppinsNormalStyle12Gray2)
}
}
}
}