kotlin 如何在编写中禁用ExposedDropdownMenuBox

fkvaft9z  于 2022-11-25  发布在  Kotlin
关注(0)|答案(1)|浏览(466)

我想基于布尔变量禁用ExposedDropdownMenuBox
我的代码看起来像这样:

@Composable
private fun Title(
    title: String,
    onTitleChange: (String) -> Unit,
    isTitleEnabled: Boolean
) {
    val options = stringArrayResource(id = R.array.name_titles)
    var expanded by remember { mutableStateOf(false) }
    var selectedOptionText by remember { mutableStateOf(title) }

    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = {
            expanded = !expanded
        }
    ) {
        TextField(
            enabled = isTitleEnabled,
            modifier = Modifier
                .fillMaxWidth()
                .greyBordered(),
            readOnly = true,
            value = selectedOptionText,
            onValueChange = { },
            label = { Text(stringResource(id = R.string.input_hint_title)) },
            trailingIcon = { TrailingIcon(expanded = expanded) },
            colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors(
                textColor = navyBlue,
                focusedLabelColor = nightGray,
                backgroundColor = white,
                cursorColor = navyBlue,
                trailingIconColor = nightGray,
                focusedTrailingIconColor = nightGray,
                focusedBorderColor = Color.Transparent,
                unfocusedBorderColor = Color.Transparent,
                disabledBorderColor = Color.Transparent,
            )
        )
        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
        ) {
            options.forEach { selectionOption ->
                DropdownMenuItem(
                    onClick = {
                        selectedOptionText = selectionOption
                        onTitleChange(selectionOption)
                        expanded = false
                    }
                ) {
                    Text(text = selectionOption)
                }
            }
        }
    }
}

因此,我有一个包含ExposedDropdownMenuBox的组合函数,其中包含textField和ExposedDropdownMenu,我想要实现的是,只要isTitleEnabled变量为true,就能够启用ExposedDropdownMenuBox,而只要isTitleEnabled变量为false,就不能展开ExposedDropdownMenuBox。

n53p2ov0

n53p2ov01#

您可以在onExpandedChange中使用条件来避免展开ExposedDropdownMenuBox。当用户单击ExposedDropdownMenuBox时调用此回调。在这种情况下,您也可以删除trailingIcon
类似于:

var isTitleEnabled by remember { mutableStateOf(false) }

ExposedDropdownMenuBox(
    expanded = expanded,
    onExpandedChange = {
        if(isTitleEnabled) {
            expanded = !expanded
        }
    }
) {
    TextField(
        enabled = isTitleEnabled,
        readOnly = true,
        trailingIcon = {

            if (isTitleEnabled){
                ExposedDropdownMenuDefaults.TrailingIcon(
                    expanded = expanded,
                    )
            }
        },

相关问题