You can auto format a phone number in a text field in your app, saving users time by formatting the phone number as they input digits. Follow this guidance to auto format a phone number:
- Create the text field.
- Auto-format a number in the text field.
Version compatibility
This implementation requires that your project minSDK be set to API level 21 or higher.
Dependencies
Create the text field
First, configure the TextField
. This example shows a phone number
formatted per the North American Numbering Plan
(NANP).NanpVisualTransformation
formats a raw string of numbers to NANP, eg.
1234567890 to (123) 456-7890.
Key points about the code
- A
TextField
composable where theonValueChange
uses a regular expression to remove all non-numeric characters and limits the length to a maximum of 10 characters before updating thephoneNumber
state. - The
TextField
has a customVisualTransformation
instance set on thevisualTransformation
attribute.NanpVisualTransformation
, the custom class instantiated here, is defined in the following section.
Auto-format a number in the text field
To format a raw string of numbers, use the implementation of the custom
NanpVisualTransformation
class:
Key points about the code
- The
filter()
function inserts the non-numeric formatting characters at the appropriate places. - The
phoneNumberOffsetTranslator
object contains two methods. One maps the offsets between the original string and the formatted one, and the other does the reverse mapping. These mappings enable the skipping of the formatting characters when the user changes the cursor location in the text field. - The formatted string and
phoneNumberOffsetTranslator
are used as arguments for aTransformedText
instance that is returned and used by theTextField
to perform the formatting.
Results
![An auto-formatted phone number in the text field](https://developer.android.google.cn/static/quick-guides/content/nanp_formatter.gif?authuser=7)
Parent collections
![](https://developer.android.google.cn/static/images/quick-guides/collection-illustration.png?authuser=7)
Display text
Text is a central piece of any UI. Find out different ways
you can present text in your app to provide a delightful user experience.
![](https://developer.android.google.cn/static/images/quick-guides/collection-illustration.png?authuser=7)
Request user input
Learn how to implement ways for users to interact
with your app by entering text and using other means of input.
Have questions or feedback
Go to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts.