Using the same click event for one or more Views in the XML
suggest changeWhen 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).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents