2017-09-26 122 views
0

我想在EditText上添加一些TextWatchers,但我應該在需要時刪除它們。從EditText刪除所有TextWatchers

... 

@BindView(R.id.widget_search_edittext) 
MaterialEditText mEditText; 

private List<TextWatcher> textWatcherList; 

... 

public void addTextChangedListener(TextWatcher watcher) { 
    textWatcherList.add(watcher); 
    mEditText.addTextChangedListener(watcher); 
} 

public void removeAllTextChangedListeners() { 
    for (TextWatcher watcher : textWatcherList) { 
     mEditText.removeTextChangedListener(watcher); 
    } 
    textWatcherList.clear(); 
}  

但這並沒有工作,任何ideias?

回答

1

請確保在擴展的TextWather類中覆蓋equals()。因爲通過調用依賴於equals函數的arraylist.indexOf(watcher)來移除存儲在arrayList abd中的觀察者。

public void addTextChangedListener(TextWatcher watcher) { 
    if (mListeners == null) { 
     mListeners = new ArrayList<TextWatcher>(); 
    } 
    mListeners.add(watcher); 
} 
/** 
* Removes the specified TextWatcher from the list of those whose 
* methods are called 
* whenever this TextView's text changes. 
*/ 
public void removeTextChangedListener(TextWatcher watcher) { 
    if (mListeners != null) { 
     int i = mListeners.indexOf(watcher); 
     if (i >= 0) { 
      mListeners.remove(i); 
     } 
    } 
} 

看看如何TextView的去除看守內部

+0

當我嘗試刪除觀察者的等於它從來不叫 –

+1

發佈您的代碼,請 –

+0

我只是tryied把一個破發點在那裏進行測試。但調試器永遠無法達到它。 @Override public boolean equals(Object obj){if(obj instanceof MyMaskWatcher){ return true; } else { return false; } } –