android textwatcher 获取当前控件,android api解析之TextWatcher
開發android有幾年了,但是從來沒有整理過,一直是寫寫寫.從今天起開始慢慢整理,總結之處如有錯誤請指出,謝謝
TextWatcher在什么時候會被調用?
TextWatcher在edittext內容發生變化時會被調用
TextWatcher一共有三個方法
beforeTextChanged(CharSequence s, int start, int count, int after)
在文本變化前調用,start代表開始變化的位置,count代表變化的字符長度.after代表變化后字符該位置字符數量
onTextChanged(CharSequence s, int start, int before, int count)
在文本變化時調用,此時s的內容已發生改變,start代表開始變化的位置,before代表變化前該位置字符數量,count代表變化了的字符長度
afterTextChanged(Editable s)
在文本變化后調用,s即為變化后的文本結果
例子:
在空白輸入框中輸入一個字符
Paste_Image.png
第一條的意思是初始長度為0,變化的位置為0,變化的字符為0,變化后此位置為字符長度為1
第二條意思是此時字符長度為1,變化的位置為0,變化前字符長度為0,變化字符數量為1
第三條意思是變化結束后字符長度為1
下面是個小demo,實現了edittext信用卡格式,主要用到了TextWatcher和Editable的一些方法
GIF.gif
public class CreditCardView extends EditText {
public CreditCardView(Context context) {
super(context);
init();
}
public CreditCardView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CreditCardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
this.addTextChangedListener(setTextWatcher());
}
private TextWatcher setTextWatcher() {
TextWatcher textWatcher = new TextWatcher() {
//記錄是否為刪除
boolean isDel = false;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.d("find", "beforeTextChangedlength=="+s.length() + ",start==" + start + ",count==" + count + ",after==" + after);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("find", "onTextChangedlength=="+s.length() + ",start==" + start + ",before==" + before + ",count==" + count);
if (before > count) {//刪除
isDel = true;
} else {
isDel = false;
}
}
@Override
public void afterTextChanged(Editable s) {
Log.d("find", "afterTextChangedlength=="+s.length());
if (!isDel && s.length() > 0 &&s.length()>1&& (s.length()) % 5 == 0) {
//在指定位置之前插入
s.insert(s.length()-1,"-");
}
if (isDel && s.length() > 0&&s.length()>1 && (s.length()) % 5 == 0) {
//刪除指定位置開區間[start,end)
s.delete(s.length() -1,s.length());
}
}
};
return textWatcher;
}
}
總結
以上是生活随笔為你收集整理的android textwatcher 获取当前控件,android api解析之TextWatcher的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [css] OOCSS有哪些好处?对应
- 下一篇: [css] css中class和id选