TextWatcher的使用
TextWatcher是一個監聽字符變化的類。當我們調用EditText的addTextChangedListener(TextWatcher)方法之后,就可以監聽EditText的輸入了。
在new出一個TextWatcher之后,我們需要實現三個抽象方法:
?
beforeTextChanged 文本改變前
onTextChanged???? 文本改變之時
afterTextChanged? 文本改變之后
?
// s是文本改變前的內容 // count刪除內容時是刪除字符的個數,增加內容時為0// after增加內容時是增加字符的個數,刪除內容時為0// 通過組件索引獲得的text內容是改變前的@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {} // s是文本改變后的內容 // start是文本改變操作后輸入光標所在位置 // count增加內容時是增加字符的個數,刪除內容時為0// after刪除內容時是刪除字符的個數,增加內容時為0// 通過組件索引獲得的text內容是改變后的@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
?
// s是文本改變后的內容
public void afterTextChanged(Editable s) {}?
TextWatcher的使用方法
//所有繼承自TextView的類
textView.addTextChangedListener(new TextWatcher() {@Overridepublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {}@Overridepublic void afterTextChanged(Editable s) {}});?
注意事項 :
在回調方法中獲取的新字符串雖然已經設置到TextView中,但是還未在UI界面中更新.
有2種情況會觸發TextWatcher的3個回調方法,setText()和EditText鍵盤輸入
如果在回調方法中調用setText(),會進入無限循環,需要增加判斷條件
afterTextChanged中去改變Editable s的值會觸發TextWatcher的3個回調方法,會進入無限循環,需要增加判斷條件
Editable s和CharSequence s獲取的數據為去除空格和回車之后字符串.
總結
以上是生活随笔為你收集整理的TextWatcher的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [vue] 你知道vue的模板语法用的是
- 下一篇: 工作286:v-model没有值会报错