如何在textwatcher旁边检索回收站视图项位置?

时间:2017-06-27 20:39:12

标签: android android-recyclerview recycler-adapter

我在检索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) {

        }

    }

持有人实施课程,我设置了观察者:

 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);

1 个答案:

答案 0 :(得分:1)

由于您在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);

}