Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add listener vs set listener

Tags:

java

android

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?)

like image 855
Vivart Avatar asked May 02 '11 08:05

Vivart


2 Answers

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.

like image 193
aioobe Avatar answered Oct 22 '22 19:10

aioobe


aioobe is right, of course. But there is an additional consideration:

According to the JavaBeans standard

  • getX / isXyz and setXyz define properties (see PropertyDescriptor) but
  • addXyzListener, removeXyzListener and getXyzListeners are also standard naming conventions for Event Listeners (see EventSetDescriptor)

So setXyzListener() is not a valid method name to set a listener according to the JavaBeans standard! Of course you may choose to violate the JavaBeans standard intentionally, but I am trying to keep you from doing it unintentionally :-)

like image 37
Sean Patrick Floyd Avatar answered Oct 22 '22 20:10

Sean Patrick Floyd