gpt4 book ai didi

android - 如何在文本观察器中检索回收器 View 项目位置?

转载 作者:行者123 更新时间:2023-11-30 00:29:07 24 4
gpt4 key购买 nike

我在检索 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 实例并在 onBindViewHolder() 覆盖中调用 addTextChangedListener():

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

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

}

关于android - 如何在文本观察器中检索回收器 View 项目位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44789449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com