0

I am writing an Android Application which outputs some array of buttons dynamically. My question is how to implement onClickListener() functionality for Array Of Buttons. I mean how to recognize the button that is clicked in public void onClick() method ? I need to display a toast based on the button that is clicked.

2 Answers 2

2

The onClick() method is passed the View that was clicked...

public void onClick(View v) {
...
}

Use v.getId() to return the button's identifier.

Sign up to request clarification or add additional context in comments.

Comments

1

you could create a class derived from OnClickListener, that, in the constructor, takes the button ID.

Something like:

class MyClickListener extends OnClickListener() {
    int buttonId;  

    MyClickListener(int id) {  
        buttonId = id;  
    }  

    protected void onClick(View v) {  
        ... // do something with buttonId
    }  
}

Then, in your onCreate, you would do:

int i, nb = mButtons.size(); // if mButtons is a List<Button>
for (i = 0; i < nb; i++) {
    mButtons.get(i).setOnClickListener(new MyClickListener(i));
}

1 Comment

Benoit Duffez .Very Good.Nice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.