How to handle button clicks using the XML onClick within Fragments
android, android-fragments, button, xml
Solution
You could just do this:
Activity:
Fragment someFragment;
//...onCreate etc instantiating your fragments
public void myClickMethod(View v) {
someFragment.myClickMethod(v);
}
Fragment:
public void myClickMethod(View v) {
switch(v.getId()) {
// Just like you were doing
}
}
In response to @Ameen who wanted less coupling so Fragments are reuseable
Interface:
public interface XmlClickable {
void myClickMethod(View v);
}
Activity:
XmlClickable someFragment;
//...onCreate, etc. instantiating your fragments casting to your interface.
public void myClickMethod(View v) {
someFragment.myClickMethod(v);
}
Fragment:
public class SomeFragment implements XmlClickable {
//...onCreateView, etc.
@Override
public void myClickMethod(View v) {
switch(v.getId()){
// Just like you were doing
}
}
Problem
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?