RecyclerView Item Edit 复用问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/silencezmz/article/details/83006935

RecyclerView Item Edit 复用问题


RecyclerView 列表控件 传承了ListView GridView Item 复用的机制 在滑动屏幕时更新数据 共用一套或者特定的几套View Holder展示数据 。。。

ViewHolder 加载数据

  • Item 加载List 展示数据
  • Item 中包含交互输入的View List数据交互
  • Item 中包含交互输入的View List数据没有交互

如果Item 交互控件 没有和List数据交互(保存/清除)在复用的机制上就会出现重复 错乱的问题,回想 ListView GridView 的Adapter ViewHolder 上都绑定了Tag 将数据直接定位到展示的ViewHolder。。。

EditText 输入信息的监听

 /**
 * Adds a TextWatcher to the list of those whose methods are called
 * whenever this TextView's text changes.
 * <p>
 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
 * not called after {@link #setText} calls.  Now, doing {@link #setText}
 * if there are any text changed listeners forces the buffer type to
 * Editable if it would not otherwise be and does call this method.
 */
public void addTextChangedListener(TextWatcher watcher) {
    if (mListeners == null) {
        mListeners = new ArrayList<TextWatcher>();
    }

    mListeners.add(watcher);
}
  • 添加 TextWatcher

      /**
       * Removes the specified TextWatcher from the list of those whose
       * methods are called
       * whenever this TextView's text changes.
       */
      public void removeTextChangedListener(TextWatcher watcher) {
          if (mListeners != null) {
              int i = mListeners.indexOf(watcher);
    
              if (i >= 0) {
                  mListeners.remove(i);
              }
          }
      }
    
  • 删除 TextWatcher

解决方案:

  • 在绑定数据的时候 先检测 view.getTag() 是否存在TextWatcher 如果存在 删除之前的绑定

  • 添加之前存储的Index ->ViewHolder 下的数据

  • 添加 新的监听 添加新的Tag view.setTag(textWatcher)

      if (((TwoViewHolder) holder).mEditQuestion.getTag() instanceof EditInputCallBack) {
                  ((TwoViewHolder) holder).mEditQuestion.removeTextChangedListener((TextWatcher)
                          ((TwoViewHolder) holder).mEditQuestion.getTag());
              }
    
              if (editInputModel != null && editInputModel.size() > 0) {
                  String str = editInputModel.get(index);
                  ((TwoViewHolder) holder).mTxtQuestion.setText(questionContent != null ? position + "、 " + questionContent : "");
                  ((TwoViewHolder) holder).mEditQuestion.setText(str != null ? str : "");
              } else {
                  ((TwoViewHolder) holder).mTxtQuestion.setText(questionContent != null ? position + "、 " + questionContent : "");
                  ((TwoViewHolder) holder).mEditQuestion.setText(answer != null ? answer : "");
              }
    
       	
              ((TwoViewHolder) holder).mEditQuestion.addTextChangedListener(callBack);
              ((TwoViewHolder) holder).mEditQuestion.setTag(callBack);
    

猜你喜欢

转载自blog.csdn.net/silencezmz/article/details/83006935