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

suggest change

When we create any View in a layout, we can use the android:onClick attribute to reference a method that handles the click. The method is resolved on the Activity, not on a Fragment.

XML Layout

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="doSomething" />

<!-- This works with any subclass of View, not just Button. -->
<ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="doSomething" />

Activity 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 a different method for each View. In that case you do not have to check the id.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents