To simplify the scenario, let us implement visual transformation for a local Cameroon phone number. A Cameroonian phone number has 9 digits, that is of the form,
We want it to be transformed to
For Jetpack Compose, we will have to implement the VisualTransformation interface. Let us have the full source code and have the explanation below
The offset mapping works such that the method originalToTransformed converts offsets in the original text to transformed text while the method transformedToOriginal converts offsets in the transformed text to original.
The method filter which is what is required returns TransformedText and we are done. You can use the same concepts for input fields like credit card,password transformation, etc.
Let us finalize by creating simple composable and preview on device and type in the text field
That is all required. You can check the VisualTransformation samples to understand better and gain more insights.
A little update: The initial code when the post was initially released for the default case returns 10 and 8 respectively in the methods originalToTransformed and transformedToOriginal. This has been updated to return the 11 and 8 respectively which are the lengths of the strings. Doing so places the cursor at the end of the input field correctly.This is thanks to the this Twitter thread.