https://kotlinlang.org logo
#compose
Title
# compose
k

Kshitij Patil

12/22/2020, 3:55 PM
Is it possible to lock user input to Captial Letters only? capitalisation parameter in Keyboard Options launches keyboard with capital letters but also allows the user to toggle it back to lowercase. Should I use visualization transformation here?
c

Casey Brooks

12/22/2020, 4:27 PM
Calling
.toUpperCase()
on the text when updating the state emitted should do it. The TextField itself doesn’t need to have explicit options for things like this, since you are entirely in control of how it displays and what happens when input is entered
Copy code
val textState = remember { mutableStateOf(TextFieldValue()) }
TextField(
    value = textState.value,
    onValueChange = { textState.value = it.copy(text = it.text.toUpperCase()) },
)
👍 1
k

Kshitij Patil

12/22/2020, 4:54 PM
Yeah I was just concerned that it might look inconsistent, you're operating a keyboard with lowercase letters and they're getting printed as uppercase.
s

Siyamed

12/22/2020, 4:54 PM
Do not use imho visual transformation since it needs a mapping between the lowercase version and uppercase version, and the capitalization rules for some characters might create trouble for you there.
d

Dominaezzz

12/22/2020, 5:21 PM
Are you suggesting to outright reject non capital letters?
s

Siyamed

12/22/2020, 5:22 PM
No, what Casey wrote sounds good.
It was about VisualTransformation api
d

Dominaezzz

12/22/2020, 5:25 PM
Ah, fair enough.
c

Casey Brooks

12/22/2020, 5:37 PM
Outright rejecting non-capital letters would be easy enough using the same technique. Check if the text in
onValueChange
contains non-capital characters, and only assign
textState.value
if it passes validation
Copy code
val textState = remember { mutableStateOf(TextFieldValue()) }
TextField(
    value = textState.value,
    onValueChange = {
        if(it.text.matches("[A-Z]*".toRegex())) {
            textState.value = it 
        }
    },
)
d

Dominaezzz

12/22/2020, 5:52 PM
Using
isErroroValue
might have better UX.
👆 1
2 Views