我有一个listview,其中包含每个位置的edittext。我为每个edittext分配了一个textwatcher,如下所示:
holder.prodQuantity.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(isDialog) {
recallMap.put(productId, s.toString());
}
}
这里的问题是,每当我向第一个编辑文本添加值时,文本观察者就会触发列表视图的所有项目。 recallMap
应该只包含所选行的id和在该行的编辑文本中输入的值,但在这种情况下,recalMap
具有所有id和在第一个编辑文本中输入的值。请注意,这是在没有任何滚动的情况下发生的。任何帮助将非常感激。谢谢。
在适配器中添加textChangedListner之前,先删除已添加的textChangedListener到该EditText。喜欢
holder.prodQuantity.removeTextChangedListener(textWatcher);
// obviously you also need to maintain TextWatchers ArrayList associated with each EditText.
// Or instead of maintaining a separate ArrayList for TextWatcher, you can implement in your Data Model Class.
然后你的代码如下
holder.prodQuantity.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(isDialog) {
recallMap.put(productId, s.toString());
}
}
使用此自定义类
public class MyCustomEditTextListener implements TextWatcher {
private int position;
public void updatePosition(int position) {
this.position = position;
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void afterTextChanged(Editable editable) {
//your edittext text is here
}
}
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout, parent, false);
return new ViewHolder(v, new MyCustomEditTextListener(), this);
}
将侦听器分配给edittext
edittext.addTextChangedListener(myCustomEditTextListener);
更新清单位置
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.myCustomEditTextListener.updatePosition(position);
}