I'm a total beginner in coding for Android and java in general and so far in various tutorials I found two ways of handling buttons being clicked.
The first one:
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//do your thing
}
});
The second one involves putting android:onClick="someMethod"
in a button's properties in the main.xml and then simply creating the method someMethod
in the activity.
I was wondering what is the difference in those two approaches. Is one better than another? Or do they work only subtly differently? To me they seem to do the same :P
Thank!
The result is same. But difference is in readability of code.
this approach i don't recommend to you.
I recommend to you use
anonymous classes
like you meant above.Also your class can implement for example
View.OnClickListener
and then you only have to implementonClick()
method and you can have one method for many widgets.I think this is also good practice, you have only one method and code have less lines and is cleaner.
When you use android:onClick="someMethod", the method is on the activity that holds the clicked view. If you're using this on a list item, it'll be more convenient (in some cases) to have the click handled on the activity. If you'll use the anonymous class approach, you'll need to set it on the adapter, which not always have access to the activity (and if so - it could get messy..). So if you need stuff from the activity that's holding you list (holding that clickable item) - I think it'll be cleaner to use the android:onClick approach.
Besides that - it's pretty much the same. Be sure to document the methods you call with android:onClick, since it's sometimes hard to track their source later.
To handle double click on android button
In first one: You are defining a method pragmatically, that will be called at every press of the button. In Second one: you are mentioning method name of the activity that will called when button will be pressed.
It totally depends upon your preference which way you like to set a click listener.
Personally, I like to set click listener pragmatically, so that I know which code will execute at onClick of a Button, while going through code.