How to handle button clicks using the XML onClick within Fragments
Asked 07 September, 2021
Viewed 1.2K times
  • 62
Votes

Pre-Honeycomb (Android 3), each Activity was registered to handle button clicks via the onClick tag in a Layout's XML:

android:onClick="myClickMethod"

Within that method you can use view.getId() and a switch statement to do the button logic.

With the introduction of Honeycomb I'm breaking these Activities into Fragments which can be reused inside many different Activities. Most of the behavior of the buttons is Activity independent, and I would like the code to reside inside the Fragments file without using the old (pre 1.6) method of registering the OnClickListener for each button.

final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Perform action on click
    }
});

The problem is that when my layout's are inflated it is still the hosting Activity that is receiving the button clicks, not the individual Fragments. Is there a good approach to either

  • Register the fragment to receive the button clicks?
  • Pass the click events from the Activity to the fragment they belong to?

19 Answer