Lalith
Lalith

Reputation: 20534

Attaching multiple listeners to views in android?

Is it possible to attach multiple onClick listeners to buttons in android? Example:

btn1.setOnClickListener(listener1);
btn1.setOnCliclListener(listener2);

And when the button is clicked onClick event of both listener1 and listener2 are triggered?

In normal GUI applications I know that we can attach more than one event handler for an event. Is it possible for android too or is there any restrictions?

Regards, Lalith

Upvotes: 36

Views: 31819

Answers (6)

Stack Diego
Stack Diego

Reputation: 1337

This is what I'll do in Kotlin:

arrayListOf(
        view1,
        view2,
        view3
    ).forEach { it.setOnClickListener { /*do stuff here*/ } }

very readable, and copy-paste error safe.

Upvotes: 0

Tom
Tom

Reputation: 311

An easy way to achieve this would be simply do:

btn1.setOnClickListener(new View.OnClickListener(){
 @Override
 public void onClick(View v) {  
   listener1.onClick(v);
   listener2.onClick(v);
}})

Or call listener2.onClick(v) inside the definition of your listener1

Upvotes: 1

John Kamau
John Kamau

Reputation: 37

Should someone bump into a similar problem, try this out:

private void setClickListeners(View view, List<View.OnClickListener> clickListeners){
    view.setOnClickListener(v -> {
        for(View.OnClickListener listener: clickListeners){
            listener.onClick(v);
        }
    });
}

Upvotes: 4

Tsunaze
Tsunaze

Reputation: 3254

Nope, for example just do this :

Set Listener:

btn.setOnClickListener(this);

Implement Method:

public void Onclick(View arg0){

   // check your id and do what you want
}

Upvotes: -5

Mike
Mike

Reputation: 31

public void onClick(View v) {
    if(v.getId() == R.id.button1) {
        // do this
    }else if(v.getId() == R.id.button2) {
        // do that
    }
}

Upvotes: -1

CommonsWare
CommonsWare

Reputation: 1006789

Android only supports one registered listener in general. However, you can easily create a listener that simply forwards the events to other listeners using the composite pattern.

Upvotes: 51

Related Questions