Hello, can't seem to wrap my head around this, ......
# compose
k
Hello, can't seem to wrap my head around this, ... all i want to do is append a hyphen(a form of separator) after every double digit entered. this's part of my custom textfield
Copy code
input = numberValidationState.text,
onValueChange = {
    numberValidationState.text = numberValidationState.autoHyphenate(it)
    numberValidationState.enableShowErrors()
},
textFieldState = numberValidationState,
and this is my extension function to do the trick
Copy code
fun String.appendHyphen(): String {
    val formattedInput = StringBuilder()
    this.filter { it.isDigit() }.forEachIndexed { index, char ->
        formattedInput.append(char)
        if ((index + 1) % 2 == 0) {
            formattedInput.append("-")
        }
    }
    return formattedInput.toString()
}
just that this trick is being tricky. The cursor appears behind the separator when its appended and entering another number reverses whatever the user intends to input. So 45 becomes 54 and this mistake gets carried on. Somebody kindly help me.
d
maybe VisualTransformation is what you're looking for (works with BTF1)? There is a credit card transformation example that adds a separator every 4 digits
k
i appreciate this Dmitry, will mosdef look into it
m
Yeah, changing the text that is inputted breaks the keyboard, which is why Compose created BTF2 which doesn't let you do that anymore. https://proandroiddev.com/basictextfield2-a-textfield-of-dreams-1-2-0103fd7cc0ec
k
will give this a read also. thanks Michael
z
If you actually want to store those hyphens in your model in BTF1, you’d also need to update the cursor position after appending them. Use TextFieldValue for that. But btf2 will handle this better