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

manueldidonna

05/22/2020, 12:02 PM
I'm having some trouble on limiting the number of chars of a TextFieldValue.
Copy code
var selection by state { TextRange(0, 0) }
var text by state { repository.getText() }
TextField(
    value = TextFieldValue(text, selection),
    onValueChange = { 
        selection = it.selection
        // there is a a limit on the number of chars. 
        // The passed text is automatically truncated
        text = repository.updateText(it.text) 
    }
)
When I exceed the number of chars, I have some problems with the keyboard that continues to record the inputs, so I have to press the delete button more times than needed.
l

Leland Richardson [G]

05/22/2020, 4:48 PM
can you file a bug on this? This use case should work properly. Thanks
v

Val Salamakha

05/26/2020, 7:19 AM
If you would like to limit your text in TextField according to a selected range, you need to do it before TextField. For example using the extract from TextField as following:  var value by state { TextFieldValue( “123456789”, selection = TextRange(0,5) )*}* val fullModel = state { EditorValue() } if (fullModel.value.text != value.text || fullModel.value.selection != value.selection) {   val newSelection = TextRange(     value.selection.start._coerceIn_(0, value.text.length),     value.selection.end._coerceIn_(0, value.text.length)   )   fullModel.value = EditorValue(     text = value.text,     selection = newSelection   ) } val text = fullModel.value.getSelectedText() value = TextFieldValue(text)   _TextField_(     value = value,     onValueChange = {     },     modifier = Modifier._preferredSize_(width = 200.dp, height = 56.dp)   )
2 Views