Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button setOnClickListener() vs android:onclick

Tags:

android

button

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?

like image 494
Mark Buikema Avatar asked Mar 04 '14 12:03

Mark Buikema


People also ask

Is onClick deprecated in Android?

onClick is prompted deprecated.

What is the difference between OnClickListener and setOnClickListener?

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.

What does setOnClickListener do in Android?

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.

Why is setOnClickListener not working?

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.


1 Answers

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.

like image 127
gilonm Avatar answered Oct 15 '22 07:10

gilonm