Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between OnClick() event and OnClickListener?

Tags:

I'm always using onclick() event in most of my projects. But, I read about OnClickListener(). Can anyone tell what's the difference between these two? And which one is best to use in Android application?.

like image 728
Praveenkumar Avatar asked Sep 17 '11 07:09

Praveenkumar


People also ask

What is the difference between Onclick and click?

click is a function on HTML elements you can call to trigger their click handlers: element. click(); onclick is a property that reflects the onclick attribute and allows you to attach a "DOM0" handler to the element for when clicks occur: element.

What is an OnClickListener?

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 is new view OnClickListener ()?

View.OnClickListener is an interface, you don't call it, but creates a new instance of it ( new View.OnClickListener() is a call to the constructor) The instance you create is of anonymous class that implements View.OnClickListener , in the brackets right under new View.OnClickListener()


2 Answers

I'm not sure the question is clear. View.OnClickListener is an interface, which defines the onClick(View) method. If you have a class which intends to listen for clicks, you should both implement the interface (if not already extending a class that does), and implement this method too. You have to use both; they're not somehow alternatives.

like image 110
Sean Owen Avatar answered Sep 20 '22 02:09

Sean Owen


OnClickListener is the interface you need to implement and can be set to a view in java code.

Lately android added a xml attribute to views called android:onclick, that can be used to handle clicks directly in the view's activity without need to implement any interface.

Both function the same way, just that one gets set through java code and the other through xml code.

like image 22
Ronnie Avatar answered Sep 22 '22 02:09

Ronnie