[java] How is using OnClickListener interface different via XML and Java code?

Possible Duplicate:
Difference between OnClick() event and OnClickListener?

I'm semi-new to Android development and when I first started I tried to avoid using the xml layout by any means necessary so some of my earlier projects involve buttons that explicitly create an OnClickListener and implement it as an anonymous inner class. Such as -

final Button button = new Button(this);
button.setText("Click to change second line of text");

OnClickListener buttonListener = new View.OnClickListener() {
    boolean clicked = false;
    int numClicks = 0;

    @Override
    public void onClick(View v) {
        if(numClicks > 5) {
            button.setText("STOP IT");
        }
        numClicks++;
        if(clicked == false){
            clicked = true;
            tv2.setText("Text Changed on Button Click");    
        }
        else
        {
            clicked = false;
            tv2.setText("Click again");
        }       
    }
};
button.setOnClickListener(buttonListener);

But as I got more familiar with android, I began to understand the value of the xml layouts and implemented buttons like this

    <Button
    android:id="@+id/button1"
    android:layout_height = "wrap_content"
    android:layout_width ="wrap_content"
    android:text = "lets do this"
    android:onClick = "DoIt"
    />

In the layout xml, where DoIt was defined in the java.

My question is, are these 2 methods functionally the same thing? Is there an OnClickListener being defined by the compiler somewhere behind the scenes? Are there any features you trade off by using one way or the other?

This question is related to java android xml android-layout android-button

The answer is


using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener then add the variable Button button1; then add this to your onCreate()

button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);

when you implement OnClickListener you need to add the inherited method onClick() where you will handle your clicks


Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to android-button

How to change the color of a button? Why is my Button text forced to ALL CAPS on Lollipop? Coloring Buttons in Android with Material Design and AppCompat Android Material Design Button Styles How to custom switch button? Android button with icon and text Android Fragment onClick button Method How do I open a new fragment from another fragment? Change Screen Orientation programmatically using a Button Android button background color