Android Button Using the same click event for one or more Views in the XML

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

When we create any View in layout, we can use the android:onClick attribute to reference a method in the associated activity or fragment to handle the click events.

XML Layout

<Button android:id="@+id/button"
    ...
    // onClick should reference the method in your activity or fragment
    android:onClick="doSomething" />

// Note that this works with any class which is a subclass of View, not just Button
<ImageView android:id="@+id/image"
    ...
    android:onClick="doSomething" />

Activity/fragment code

In your code, create the method you named, where v will be the view that was touched, and do something for each view that calls this method.

public void doSomething(View v) {
    switch(v.getId()) {
        case R.id.button:
            // Button was clicked, do something.
            break;
        case R.id.image:
            // Image was clicked, do something else.
            break;
    }
}

If you want, you can also use different method for each View (in this case, of course, you don't have to check for the ID).



Got any Android Question?