天天看點

Android 完美實作手機号344格式化效果

一、前言:

在展示手機号碼的時候,會遇到手機号按照344格式效果,這種效果的實作遇到過兩次了,也踩過了許多的坑,在這裡記錄一下一個完美實作這種效果的方式。輸入、插入、删除等光标位置停留比較好的互動效果。

二、效果:

關于輸入空格崩潰的情況在簡書有修複

https://www.jianshu.com/p/1c949029d6b2

三、代碼實作:

public class ZpPhoneEditText extends AppCompatEditText implements TextWatcher {

    // 特殊下标位置
    private static final int PHONE_INDEX_3 = 3;
    private static final int PHONE_INDEX_4 = 4;
    private static final int PHONE_INDEX_8 = 8;
    private static final int PHONE_INDEX_9 = 9;

    public ZpPhoneEditText(Context context) {
        super(context);
    }

    public ZpPhoneEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ZpPhoneEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        super.onTextChanged(s, start, before, count);
        if (s == null || s.length() == 0) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (i != PHONE_INDEX_3 && i != PHONE_INDEX_8 && s.charAt(i) == ' ') {
                continue;
            } else {
                sb.append(s.charAt(i));
                if ((sb.length() == PHONE_INDEX_4 || sb.length() == PHONE_INDEX_9) && sb.charAt(sb.length() - 1) != ' ') {
                    sb.insert(sb.length() - 1, ' ');
                }
            }
        }
        if (!sb.toString().equals(s.toString())) {
            int index = start + 1;
            if (sb.charAt(start) == ' ') {
                if (before == 0) {
                    index++;
                } else {
                    index--;
                }
            } else {
                if (before == 1) {
                    index--;
                }
            }

            setText(sb.toString());
            setSelection(index);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    // 獲得不包含空格的手機号
    public String getPhoneText() {
        String str = getText().toString();
        return replaceBlank(str);
    }

    private String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            if (m.find()) {
                dest = m.replaceAll("");
            }
        }
        return dest;
    }
}
           

布局XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <com.example.zpdemo.widget.ZpPhoneEditText
        android:id="@+id/et_phone"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:hint="格式化手機号344"
        android:inputType="phone"
        android:maxLength="13"/>

    <Button
        android:id="@+id/btn_phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textColor="#f00"
        android:textSize="16sp"
        android:text="獲得手機号"/>

</LinearLayout>
           

應用

private ZpPhoneEditText etPhone;
    private Button btnPhone;

    private void initView() {
        etPhone = (ZpPhoneEditText) findViewById(R.id.et_phone);
        btnPhone = (Button) findViewById(R.id.btn_phone);
        btnPhone.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                btnPhone.setText(etPhone.getPhoneText());
            }
        });
     }
           

效果杠杠的,代碼比較完整,親自嘗試一下比較好。。。