Vivart Vivart - 5 months ago 57
Android Question

add listener vs set listener

What is the difference between adding a listener and setting a listener.

e.g.

addTextChangedListener(textWatcher);
setOnClickListener(clickListener);


Answer:

After aioobe's answer i have tested this in my project.
So we can do this.

editText.addTextChangedListener(textWatcher1);
editText.addTextChangedListener(textWatcher2);


but we can't do this.(It will set only the last listener in this case clickListener2)

button.setOnClickListener(clickListener1);
button.setOnClickListener(clickListener2);


Another doubt

I am not able to think any use case in which i need two textWatcher for single editText. Can anybody give such a use case. (should i ask this question as separate question?)

Answer

If you have a set-method there's usually only one listener. (Personally I prefer to call them "handlers" though).

With add-methods you can typically have an arbitrary number of listeners.