Android 完美實現手機號344格式化效果

weixin_34087301發表於2018-03-19

一、前言:

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

二、效果:

8389878-4117f0b22d355abf.PNG
捕獲.PNG

三、程式碼:

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);  
        initView();
    }  
  
    public ZpPhoneEditText(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        initView();
    }  
  
    public ZpPhoneEditText(Context context, AttributeSet attrs, int defStyleAttr) {  
        super(context, attrs, defStyleAttr);  
        initView();
    }  

    private void initView() {
        setFilters(new InputFilter[]{
                new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, 
                                                Spanned spanned, int dstart, int dend) {
                        if (" ".equals(source.toString()) || source.toString().contentEquals("\n") || dstart == 13) {
                            return "";
                        } else {
                            return null;
                        }
                    }
                }
        });
    }
  
    @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());  
            }  
     });  
} 

效果槓槓的,程式碼比較完整,親自嘗試一下比較好。。。

相關文章