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?.
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.
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.
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()
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.
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.
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