Travis St. Onge
Travis St. Onge

Reputation: 35

Can I reference an OnClickListener's button from inside the listener? (android)

I have an android program where I have multiple buttons using the same OnClickListener, and I want to be able to reference the button's dynamically assigned text from inside the listener. Is there some way to reference the button that was pushed to get its text? I don't want to have to make multiple button-specific listeners that do the same thing.

Upvotes: 3

Views: 3022

Answers (4)

Zarjio
Zarjio

Reputation: 1137

Yes, there should be a way.

public abstract void onClick (View v)

You'll notice that the View that was clicked is passed into the onClick() method. So if you have a reference to the View (Button) available (for example, as an instance variable in the Activity) then you can do this:

public abstract void onClick (View v) {
    if (v == firstButton) {
        //Do some stuff
    }
    else if (v == secondButton) {
        //Do some other stuff
    }
}

Upvotes: 0

Anantha Sharma
Anantha Sharma

Reputation: 10098

use the View which comes as the argument to the onClick(View v)

this can be casted to a button & worked with.

Upvotes: 1

antlersoft
antlersoft

Reputation: 14786

The argument to onClick is the View that originated the click, which will be the button to which you attached the listener. Cast it to Button to get the button object.

Upvotes: 0

smoak
smoak

Reputation: 15024

In your onClick(View v) you can cast it to a button:

@Override
public void onClick(View v) {
  Button clickedButton = (Button)v;
  // do stuff with it here.
}

Upvotes: 14

Related Questions