EditText在RecyclerView的中遇到的一些问题

      每做完一个项目,就会抽时间来总结下遇到的问题,今天就写下EditText在RecyclerView中遇到的问题,也不知道这样解决是不是好办法。

1.EditText在RecyclerView会遇到什么问题呢,首先是RecyclerView复用问题,应用RecyclerView有复用机制,会导致RecyclerView中的EditText出现错乱,甚至值会发生变化。我的解决方式是每一个EditText设置一个tag,然后再输入完成的时候取出tag,具体代码就是

在Holder设置值之前设置

mTvName.setTag(position);

mTvName.addTextChangedListener(new myTextWatcher(mEdDeviceFt, 1, position)); //1代办第列,因为项目里RecyclerView一行有多个EditText,position代表第几列 myTextWatcher 是个内部类

class myTextWatcher implements TextWatcher {
        private EditText view;
        private int index;
        private int position;

        public myTextWatcher(EditText view, int index, int position) {
            this.view = view;
            this.index = index;
            this.position = position;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            int tagPosition = (int) view.getTag();
            if (position != tagPosition) return;      
        }

        @Override
        public void afterTextChanged(Editable s) {
            int tagPosition = (int) view.getTag();
            if (position != tagPosition) return;
            if (mOnItemEdChangeListener != null) {
                if(view.hasFocus()){
                    mOnItemEdChangeListener.onChange(tagPosition, index, s.toString());
                }
            }
        }
    }

这个就能解决错乱问题

2.动态添加、删减带EditView 的RecyclerView的项,同时点击选择项,进行填充数据

如下图

EditText在RecyclerView的中遇到的一些问题

这种即使用了1的方法,也会出现输入数据错乱问题。

我的解决方法是,点击选择的时候,获取它焦点,清除输入框的焦点,当输入的时候再获取焦点,这样数据不会因为点击事件的变换而变化。

mEdCount.setTag(position);
mEdCount.setOnFocusChangeListener(new myFocus(mEdCount, position));
class myFocus implements View.OnFocusChangeListener {
    private EditText view;
    private int position;

    public myFocus(EditText view, int position) {
        this.view = view;
        this.position = position;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int tagPosition = (int) view.getTag();
        if (position != tagPosition) return;
        if (hasFocus) {
            view.addTextChangedListener(new myTextWatcher(view, position));
        } else {
            view.removeTextChangedListener(new myTextWatcher(view, position));
        }
    }
}

不知道说得对不对,但是我确实这样解决了问题。