Custom input mobile phone number automatically add separator, mobile phone number Separator
A relatively simple control is to add some logic processing. Previously, it seems to be a direct listener, which is convenient for encapsulation.
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 o NTextChanged (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 ++) {// Add the delimiter 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) ;}}// prevent setting the value 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 {// judge String line = text when deleting. subSequence (text. length ()-1, text. length ()). toString (); if (line. equals (String. valueOf (CUT) {// If the '-' symbol is removed, sb is removed by default. 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
Easy to use
Then the effect is displayed.
The '-' separator is automatically filled when the fourth Delimiter is entered, and the '-' separator is automatically deleted when the fourth Delimiter is deleted.