一譬淳、前言:
今天發(fā)現(xiàn)一個怪問題直焙,在Edittext中編輯文本的時候logcat一直刷屏徘溢,打印相同的日志吞琐,導(dǎo)致頁面卡頓捆探,在afterTextChanged方法中做調(diào)用次數(shù)統(tǒng)計,確實可以觸發(fā)多次站粟。
- addTextChangedListener多次重復(fù)執(zhí)行的問題?
- RecyclerView列表中的EditText 復(fù)用問題?
效果圖如下:
二黍图、addTextChangedListener多次重復(fù)執(zhí)行的問題?:
private TextWatcher mTextWatcher;
//1、移除原來的文字改變監(jiān)聽卒蘸,避免列表刷新或者view復(fù)用所造成TextWatcher被多次調(diào)用
if (mTextWatcher !=null){
mEt.removeTextChangedListener(mTextWatcher);
}
//2 創(chuàng)建TextWatcher
mTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
//todo
}
};
//3 先移除,后添加
mEt.addTextChangedListener(mTextWatcher);
//4 設(shè)置值
mEt.setText(value);
三翻默、RecyclerView列表中的EditText 復(fù)用問題?(包含解決1的問題)
public class InStorageAdapter extends BaseQuickAdapter<InStorageBean, BaseViewHolder> {
private TextWatcher mTextWatcher;
public InStorageAdapter(int layoutResId, @Nullable List<InStorageBean> data) {
super(layoutResId, data);
}
@Override
protected void convert(@NonNull BaseViewHolder helper, InStorageBean item) {
//1缸沃、布局位置
int layoutPosition = helper.getLayoutPosition();
EditText et_number = helper.getView(R.id.et_number);
if (mTextWatcher != null) {
et_number.removeTextChangedListener(mTextWatcher);
}
mTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
//2、EditText監(jiān)聽的位置
int position = helper.getLayoutPosition();
//3修械、 輸入框可見趾牧,并且布局位置和監(jiān)聽位置一致
if (et_number.hasFocus() && position == layoutPosition) {
String str = editable.toString().trim();
if (!TextUtils.isEmpty(str)) {
int value = Integer.parseInt(str);
if (value > 0) {
//4、設(shè)置值
item.setInStorage(value);
} else {
item.setInStorage(0);
}
}
}
}
};
et_number.addTextChangedListener(mTextWatcher);
//4 展示數(shù)據(jù)
if (item.getInStorage() == 0) {
et_number.setText("");
} else {
et_number.setText(String.valueOf(item.getInStorage()));
}
}
}