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