EditText格式化11位手机号输入xxx xxxx xxxx
public static void formatPhoneInput(final EditText editText){
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s == null || s.length() == 0) return;
StringBuilder sb = new StringBuilder(s.toString());
if (before == 0){
if (sb.length() == 3 || sb.length() == 8){
sb.append(' ');
}
}
if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length()-1) != ' '){
sb.insert(sb.length() - 1, ' ');
}
if (!sb.toString().equals(s.toString())){
editText.setText(sb.toString());
editText.setSelection(sb.toString().length());
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
布局xml
<EditText
android:id="@+id/phone_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_gravity="center_horizontal"
android:maxLength="13"
android:textSize="24sp"
android:textColorHint="#aaaaaa"
android:textColor="@color/colorAccent"
android:hint="请输入11位手机号码"
android:inputType="number"/>