How to know which Button was pressed recently among all the Buttons in an activity?

If the Button are in a reusable View like ListView following way will help you.
Dynamically set tag to each Button like follow,

button1.setTag("button1");
button2.setTag("button2");
button3.setTag("button3");

Then in the onClick method,

@Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(), v.getTag()+" Clicked",
                    Toast.LENGTH_SHORT).show();
    }

If Button is in a simple Activity

 @Override
       public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                Toast.makeText(getApplicationContext()," Button 1 Clicked",
                            Toast.LENGTH_SHORT).show();
                break;
           case R.id.button2:
                Toast.makeText(getApplicationContext()," Button 2 Clicked",
                            Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
            }

            }

Leave a Comment