自訂輸入手機號自動添加分隔字元,手機號分隔字元

來源:互聯網
上載者:User

自訂輸入手機號自動添加分隔字元,手機號分隔字元

比較簡單的一個控制項,就是加些邏輯處理而已,以前貌似是直接監聽的,封裝起來方便點

public class AccountTxtView extends android.support.v7.widget.AppCompatEditText {    private final char CUT = '-';    public AccountTxtView(Context context) {        super(context);    }    public AccountTxtView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public AccountTxtView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {        if (text == null || text.length() == 0)            return;        StringBuilder sb = new StringBuilder();        for (int i = 0; i < text.length(); i++) {//添加分割符            if (i != 3 && i != 8 && text.charAt(i) == CUT) {                continue;            } else {                sb.append(text.charAt(i));                if ((sb.length() == 4 || sb.length() == 9)                        && sb.charAt(sb.length() - 1) != CUT) {                    sb.insert(sb.length() - 1, CUT);                }            }        }        //防止多次設定值        if (!sb.toString().equals(text.toString())) {            int index = start + 1;            if (sb.charAt(start) == CUT) {                if (lengthBefore == 0) {                    index++;                } else {                    index--;                }            } else {                if (lengthBefore == 1) {                    index--;                }            }            setText(sb.toString());            setSelection(index);        }else{//刪除時候判斷            String line = text.subSequence(text.length() - 1, text.length()).toString();            if (line.equals(String.valueOf(CUT))) {//如果刪除碰到‘-’符號,則預設去除                sb.deleteCharAt(text.subSequence(0, text.length() - 1).length());                setText(sb.toString());                setSelection(sb.length());            }        }    }    public String getPhone() {        String result = null;        String val = getText().toString();        if (val == null || val.isEmpty())            return "";        result = val.replace(String.valueOf(CUT), "");        return result;    }}
View Code

使用也簡單

然後效果就出來了

輸入第四個的時候自動填滿‘-’分隔字元,然後刪除的時候自動刪除‘-’分隔字元

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.