比較簡單的一個(gè)控件,就是加些邏輯處理而已,以前貌似是直接監(jiān)聽的,封裝起來方便點(diǎn)

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);
}
}
}
//防止多次設(shè)置值
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{//刪除時(shí)候判斷
String line = text.subSequence(text.length() - 1, text.length()).toString();
if (line.equals(String.valueOf(CUT))) {//如果刪除碰到‘-'符號(hào),則默認(rèn)去除
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;
}
}
新聞名稱:Android自定義輸入手機(jī)號(hào)自動(dòng)添加分隔符-創(chuàng)新互聯(lián)
文章路徑:http://chinadenli.net/article20/cosjjo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗(yàn)、手機(jī)網(wǎng)站建設(shè)、品牌網(wǎng)站制作、外貿(mào)建站、網(wǎng)站設(shè)計(jì)公司、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容