How to get id of dynamically generated button when its clicked

Viewed 87

I used a loop to create some dynamically generated buttons and in the same loop, I defined OnClickListener.

The summarized code:

for (int j = 0; j < list.size(); j++) {
    Button button = new Button(this);
    button.setId(j);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(view v) {
            //Code
        }
    });
}

If any of them are clicked, then onClick is activated and all of them run the same code. I wanna know how to get the id of clicked buttons.

2 Answers

On your onClickListener, there is a supplied View v parameter, that was basically your button, so just call: v.getId() should get your the button's id.

button.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v){
        Log.d('LOG', v.getId());
    }
}
/**
 * Interface definition for a callback to be invoked when a view is clicked.
 */
public interface OnClickListener {
    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    void onClick(View v);
}

Above interface is registered for every view setOnClickListener(), so if any user clicks the view, onClick(View v) method will be invoked. That time we get to know about all the property of the view. So, we get the Views Id by calling this method view.getId().

Related