首页 > 解决方案 > 仅允许在 TextField 中输入字符

问题描述

我试图让我的 TextField 只接受使用keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)as 的字符:

      TextField(
                value = query3.value,
                onValueChange = { newValue ->
                    query3.value = newValue
                },
                singleLine = true,
                label = {
                    Text(
                        "Bank name",
                        color = colorResource(id = R.color.bright_green),
                        fontFamily = FontFamily(Font(R.font.poppins_regular)),
                        fontSize = with(LocalDensity.current) { dimensionResource(id = 
                        R.dimen._12ssp).toSp() },
                        )
                },
                interactionSource = interactionSource,
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
                 .
                 .
                 .

但是软键盘仍然允许输入数字。如何使软键盘只允许输入字符?

标签: androidtextfieldandroid-softkeyboardandroid-jetpack-compose

解决方案


您需要过滤掉文本字段回调中的数字,

TextField(
            value = query3.value,
            onValueChange = { newValue ->
                query3.value = newValue.filter { !it.isDigit() }
            },
            singleLine = true,

推荐阅读