RecyclerView中有EditText時,設定TextWatcher發生錯亂問題
阿新 • • 發佈:2018-12-29
RecyclerView中有EditText時,設定TextWatcher發生錯亂問題
解決辦法:
- 在Adapter裡面的onBindViewHolder方法裡面先移除當前item中EditText的TextWatcher;
if (holder.editText.getTag() != null && holder.editText.getTag() instanceof TextWatcher) { holder.editText.removeTextChangedListener((TextWatcher) holder.editText.getTag()); }
- 新建一個TextWatcher,然後給當前editText新增;
TextWatcher textWatcher = 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) { String txt = holder.editText.getText().toString(); if (!TextUtils.isEmpty(txt) && !TextUtils.equals(datas.get(position).getTxt(), txt)) { data.setTxt(txt); } } }; holder.editText.addTextChangedListener(textWatcher);
- 最後給當前EditText設定Tag為當前的TextWatcher
holder.editText.setTag(textWatcher);