The difference between Android OnClick and Setonclicklistener
There are two ways to add a click event handler for the Android widgets, one is to add the onclick attribute to the XML file, and then add the corresponding function to the code. The other is to add the Setonclicklistener function directly to the code. What is the difference between them? Take the button control as an example to explain.
Method One
To add the OnClick property in XML
<relativelayout
xmlns:android= "http://schemas.android.com/apk/res/android"
android:layout_width= " Match_parent "
android:layout_height=" match_parent ">
<button
android:id=" @+id/mybutton
" Android:layout_width= "Wrap_content"
android:layout_height= "wrap_content"
android:layout_ Centerinparent= "true"
android:text= "Press Me"
android:onclick= "ButtonClick"/>
</ Relativelayout>
Add the corresponding function ButtonClick in your code, and note that you want to add to the Java class that corresponds to the current activity.
public class Mainactivity extends Appcompatactivity {
@Override
protected void OnCreate (Bundle Savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
}
public void ButtonClick {
toast.maketext (this, button is clicked, Toast.length_short). Show ();
// ....
}
Method Two
public class Mainactivity extends Appcompatactivity {
@Override
protected void OnCreate (Bundle Savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
Button button = (button) Findviewbyid (R.id.mybutton);
Button.setonclicklistener (New View.onclicklistener () {
@Override public
void OnClick (View v) {
Toast.maketext (Mainactivity.this, "button is clicked", Toast.length_short). Show ();}}
The common ground between the two
The bottom of the two is no different.
The difference between the two
Considerations for using the first method:
1. The event handler function must be public.
2. The event handler function must be defined in the activity.
3. The event handler function must have an argument of the view type.
4. Can only be used in API level 4 and later versions.
Thank you for reading, I hope to help you, thank you for your support for this site!