What is the difference between android:onClick in xml and setOnClickListener?

Asked 2 years ago, Updated 2 years ago, 140 views

There are two ways to define the onClick button on Android: adding attributes to xml and implementing setOnClick with Java code. What is the difference between these two? What else can I do?

android onclick

2022-09-22 16:50

1 Answers

Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myFancyMethod(v);
    }
});
// some more code
public void myFancyMethod(View v) {
    // // does something very interesting
}


<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click me!"
    android:onClick="myFancyMethod" />
<!-- even more layout elements -->

This is how you do it.


2022-09-22 16:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.