我也花了很多時間找到解決方案,最終最終解決了像下面這樣的標籤。 它將通過從convertView的標記獲取引用來刪除先前的TextWatcher實例。 它完美地解決了這個問題。 在你CustomAdapter文件中,設置一個新的內部類象下面這樣:
private static class ViewHolder {
private TextChangedListener textChangedListener;
private EditText productQuantity;
public EditText getProductQuantity() {
return productQuantity;
}
public TextChangedListener getTextChangedListener() {
return textChangedListener;
}
public void setTextChangedListener(TextChangedListener textChangedListener) {
this.textChangedListener = textChangedListener;
}
}
然後在你的overrided公共查看getView(INT位置,查看convertView,一個ViewGroup父)方法執行類似下面的邏輯:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
EditText productQuantity;
TextChangedListener textChangedListener;
if(convertView==null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.cart_offer_item, parent, false);
productQuantity=(EditText)convertView.findViewById(R.id.productQuantity);
addTextChangedListener(viewHolder, position);
convertView.setTag(viewHolder);
}
else
{
ViewHolder viewHolder=(ViewHolder)convertView.getTag();
productQuantity=viewHolder.getProductQuantity();
removeTextChangedListener(viewHolder);
addTextChangedListener(viewHolder, position);
}
return convertView;
}
private void removeTextChangedListener(ViewHolder viewHolder)
{
TextChangedListener textChangedListener=viewHolder.getTextChangedListener();
EditText productQuantity=viewHolder.getProductQuantity();
productQuantity.removeTextChangedListener(textChangedListener);
}
private void addTextChangedListener(ViewHolder viewHolder, int position)
{
TextChangedListener textChangedListener=new TextChangedListener(position);
EditText productQuantity=viewHolder.getProductQuantity();
productQuantity.addTextChangedListener(textChangedListener);
viewHolder.setTextChangedListener(textChangedListener);
}
然後實現如下TextWatcher類:
private class TextChangedListener implements TextWatcher
{
private int position;
TextChangedListener(int position)
{
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) {
}
@Override
public void afterTextChanged(Editable s) {
Log.d("check", "text changed in EditText");
}
}
這將通過獲取引用從標籤刪除以前的TextWatcher實例convertView
對於所有元素只有一個TextWatcher會不會更簡單? – Jodes 2011-06-07 19:41:06
如何在文本更改方法觸發時知道哪一行被修改? – GendoIkari 2011-06-07 19:48:47
@Jodes:我不認爲最好有一個TextWatcher適用於所有元素。如果你想添加/刪除它們,你需要不同的textwatchers。 – 2012-04-18 12:15:25