To register an OnClickListener
I always call setOnClickListener(listener)
on the Button
. Now I have seen a piece of code where the click event is defined in the layout, by using android:onclick="nameOfMethod"
and implement the method with a View
parameter.
Are there any differences in these two ways of adding an OnClickListener
? Which one is recommended?
onClick is prompted deprecated.
In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.
OnClickListener and wires the listener to the button using setOnClickListener(View. OnClickListener) . As a result, the system executes the code you write in onClick(View) after the user presses the button. The system executes the code in onClick on the main thread.
You need to put the setOnClickListener in one of the activity callbacks. In your onCreate() method, move the button there and then setOnClickListener() . Save this answer.
The onClick
with function binded in XML is a bind between onClick
and the function that it calls. The function will have only one argument in order for onClick
to function.
An OnClickListener
is an interface that any class could implement. Since it is an interface that any class could implement, this is more flexible.
You could easily swap one listener implementation with another if you need to.
An OnClickListener
enables you to separate the action/behavior of the click event from the View that triggers the event. While for simple cases this is not such a big deal, for complex event handling, this could mean better readability and maintainability of the code
In other words -
XML onClick
is good for one fixed implementation in your Java code.
OnClickListener
is better for more complex codes and multiple buttons. But as for the basic function - they both do the exact same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With