https://kotlinlang.org logo
Title
n

Nicolai

04/21/2023, 4:28 PM
Hi Guys 👋 . I Hope one of you can help me. Problem • Working with an OutlinedTextField in Compose to accept phone number input. • Need to format the phone number based on the country’s phone number pattern. • Once formatted, the cursor is no longer at the end of the phone number. Attempted Solution • Added a TextFieldValue with a selection TextRange at the end of the input. Issue with Attempted Solution • Prevents the user from moving the cursor. Request for Help • Looking for suggestions on how to allow the user to move the cursor. • Also need to ensure that if the user enters a valid number according to the country’s format, the cursor is set to the end.
t

Travis Griggs

04/21/2023, 4:33 PM
My guess is that you format in the
onValveChange
hook?
My tests show that this hook gets fired on both character changes as well as cursor changes (at least when you're using a TextFieldValue). So if you're updating both the string and setting the cursor to the end, you're going to clobber cursor moves.
If you add some smarts to your hook though... you can disambiguate. If the current/last value has the same text as the current one, then you can assume it's just a cursor change and just update your value. If the text property has changed, only then apply your formatting and associated cursor adjustment.
n

Nicolai

04/21/2023, 4:48 PM
That I didn’t know thank you. However, it doesn’t really help me. I still don’t know how to move the cursor without setting the TextRange(value.length). And if I do this then the cursor won’t move
t

Travis Griggs

04/21/2023, 4:58 PM
I'm not following...
onValueChange = { update -> 
  if (update.text == curentValue.text) {
    // apparently just moving the cursor, let it go through as is
    currentValue = update
  } else {
    // text changed, we'll need to format it I guess
    val formatted = format(update.text)
    currentValue = TextFieldValue(formatted, TextRange(formatted.length)
}
... or something like that