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?
Best solution IMHO:
in fragment:
then in Fragment's onViewStateRestored:
ButterKnife is probably the best solution for the clutter problem. It uses annotation processors to generate the so called "old method" boilerplate code.
But the onClick method can still be used, with a custom inflator.
How to use
Implementation
I would rather go for the click handling in code than using the
onClick
attribute in XML when working with fragments.This becomes even easier when migrating your activities to fragments. You can just call the click handler (previously set to
android:onClick
in XML) directly from eachcase
block.When it comes to handling clicks in fragments, this looks simpler to me than
android:onClick
.As I see answers they're somehow old. Recently Google introduce DataBinding which is much easier to handle onClick or assigning in your xml.
Here is good example which you can see how to handle this :
There is also very nice tutorial about DataBinding you can find it Here.
I'd like to add to Adjorn Linkz's answer.
If you need multiple handlers, you could just use lambda references
The trick here is that
handler
method's signature matchesView.OnClickListener.onClick
signature. This way, you won't need theView.OnClickListener
interface.Also, you won't need any switch statements.
Sadly, this method is only limited to interfaces that require a single method, or a lambda.
This has been working for me:(Android studio)