I'm developing application for Android. In this app user needs sign up and he needs type phone number. I want make mask for this text field in format like +7 (999) 999-99-99. I've tried use mPhoneNumberEditText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
but it provides only (999) 999-9999 format.
How can I do format which I need?

- 457
- 2
- 9
- 24
-
Please post your code what you have tried. – Rohit5k2 Feb 26 '16 at 10:27
4 Answers
The most effective way to use a mask on EditText in your Android programs in Android Studio is to use MaskedEditText
library (GitHub link).
It's a kind of custom EditText with Watcher that allows you to set a hint with different color (if you want if will be available even when user already started to type), mask and it's very easy to use :-)
compile 'ru.egslava:MaskedEditText:1.0.5'
<br.com.sapereaude.maskedEditText.MaskedEditText
android:id="@+id/phone_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:typeface="monospace"
mask:allowed_chars="1234567890"
mask:mask="+7(###)###-##-##"
app:keep_hint="true"
/>
And that is!

- 1,314
- 14
- 28
The format you are looking for is used in Russia. Use the following code for it:
String data = PhoneNumberUtils.formatNumber("9999999999", "RU");
Log.i("Number", data);
The first parameter is your number string and second one is the ISO code of the country.
Useful Links: Android Docs, Phone Number formats of different countries, ISO code of countries

- 9,517
- 7
- 36
- 67
This plugin can help:
https://github.com/pinball83/Masked-Edittext
<com.github.pinball83.maskededittext.MaskedEditText
android:id="@+id/masked_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
app:mask="+7 (***) ***-**-**"
app:notMaskedSymbol="*"/>

- 2,317
- 1
- 24
- 28
I am sharing my piece of code with to give you an idea, how could you do it.
I did it for my project a long ago, I hope you could figure out how the following number XXXXXXXXXXXXX converted into XXXXX-XXXXXXX-X in textwatcher
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
int i = et_cnic.getText().toString().length();
if (i < 6)
len = 0;
if (i == 6 && len < 7) {
len = 7;
String ss = s.toString();
String first = ss.substring(0, ss.length() - 1);
String last = ss.substring(ss.length() - 1);
et_cnic.setText(first + "-" + last);
et_cnic.setSelection(et_cnic.getText().length());
}
if (i < 14)
len2 = 0;
if (i == 14 && len2 < 14) {
len2 = 14;
String ss = s.toString();
String first = ss.substring(0, ss.length() - 1);
String last = ss.substring(ss.length() - 1);
et_cnic.setText(first + "-" + last);
et_cnic.setSelection(et_cnic.getText().length());
}
}

- 475
- 1
- 6
- 21