检索CustomWatcher内的位置时,我得到了NullPoniterExecption。
我的CustomTextWatcher类:

public static class CustomWatcher implements TextWatcher {

        private MyViewHolder hol;
        private EditText editText;

        public CustomWatcher(EditText editText) {
            this.editText = editText;
        }

        @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 position = (int)editText.getTag(R.id.id_ans_text);
            Log.d("SUB", position+" "+s);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }

    }


我设置了观察者的holder实现类:

 public class MyViewHolder extends RecyclerView.ViewHolder{

        public EditText answer;
        private int position;

        public MyViewHolder(View view) {
            super(view);
            context = view.getContext();
            answer = (EditText) view.findViewById(R.id.id_ans_text);
            Log.d("ss",answer+"");
            CustomWatcher textWatcher = new CustomWatcher(answer);
            answer.addTextChangedListener(textWatcher);
}
}


在onBindViewHolder中:

 headerHolder.answer.setTag(R.id.id_ans_text, position);

最佳答案

由于您为RecyclerView中的每个项目都有一个CustomWatcher实例,因此您只需将位置保留在实例变量中即可。

首先,修改CustomWatcher,使其将位置作为构造函数的参数:

public static class CustomWatcher implements TextWatcher {

        private MyViewHolder hol;
        private EditText editText;
        private int position;

        public CustomWatcher(EditText editText, int pos) {
            this.editText = editText;
            this.position = pos;
        }

        @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 position = (int)editText.getTag(R.id.id_ans_text);
            Log.d("SUB", position+" "+s);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
}


然后,创建CustomWatcher实例,并在addTextChangedListener()替代中调用onBindViewHolder()

@Override
public void onBindViewHolder(ViewHolder headerHolder, int position) {

    CustomWatcher textWatcher = new CustomWatcher(headerHolder.answer, position);
    headerHolder.answer.addTextChangedListener(textWatcher);

}

10-07 23:35