Advantage and advantage between onClick and setOnClickListener

Asked

Viewed 14,893 times

10

I have a certain situation where we see that it is possible to create in the XML file a property called onClick:

onClick:

XML:

<Button
android:layout_height="@dimen/edittext_min_height"
android:layout_alignParentLeft="true"
android:minWidth="120sp"
android:onClick="btnSend"
android:clickable="true"/>

Class:

public void btnSend(View view){
    //faça algo
}

On the other hand we can also instantiate within the class the setOnClickListener():

setOnClickListener:

XML

<Button
    android:id="@+id/btnSend"
    android:layout_height="@dimen/edittext_min_height"
    android:layout_alignParentLeft="true"
    android:minWidth="120sp"/>

Class:

Button btnSend = (Button) findViewById(R.id.btnSend);
btnSend .setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
      //faça algo
   }
});

What would be the advantages and disadvantages between using onClick and setOnClickListener?

  • I haven’t had a real problem yet that prevented using onClick in xml. Just a few times I had to use the same screen more than once in the program for different situations. Maybe that’s it.

  • I don’t particularly like to use the onClick in XML, because if you, for some reason, delete the method btnSend of your class, will not fail to compilation, and yes error of execution.

  • I believe that is "bad" onClick in XML because it would be necessary to create a method for each button in the layout, leaving the java code immense.

  • Actually I think the "android:onClick" was implemented in android 5 that’s the only difference.

  • @Gabriellocalhost I think the attribute android:onClick there has always been.

4 answers

12


I find only one advantage in each of them which, in turn, represent a disadvantage in relation to the other.

setOnClickListener().

  • Upside.
    Allows reuse of existing code.
    If you implement the interface in a separate class it can be reused in other similar situations.
  • Downside.
    The implementation, being done in an anonymous class, makes the code more difficult to read and maintain. Of course it is debatable and some say otherwise. In my opinion it is code that "appears out of nowhere", in the middle of the one in which I am interested to read/analyze.

onClickin XML

  • Upside.
    Easier to read code. The code is in a method declared for this purpose.
    Can avoid the need to have a field and use the findViewById()
  • Downside.
    Code cannot be reused.
    It only works when the view is used in an Activity.

For simple implementations and without the need for code to be reused, use the onClick in XML with the respective java method.
For more complex implementations and/or code reuse, create a separate class and use the setOnClickListener().

  • If I use onClick, I could dynamically change the text of this button ?

  • Text or associated code?

  • The related question is: I can only change the text of the button if I instate using the findViewById()? If there is no way, I think maybe then be a disadvantage using the onClick when I want to change the text of buttons dynamically.

  • I don’t see what the connection is between using the onClick and change the button text. Note that I say "Can avoid the need to have an attribute and use the findViewById()" and not that avoids. I think that the (main)reasons to take into account to choose one of the forms are the ones I indicate at the end of the answer

4

I believe there is only one difference or different mode of application. The methods are similar, whether you indicate your action by clicking the button on XML how to handle this action by Listener.

It turns out that by using the android:onClick the method setOnClickListener is implementing it the same way, only you don’t see it. They do the same thing. And yes, you can handle several different actions using the XML.

Take an example:

XML

<Button android:id="@+id/b_1"
    android:onClick="actionHandle"/>

<Button android:id="@+id/b_2"
    android:onClick="actionHandle"/>

Java

public void actionHandle(View v){
    switch(v.getId()){
        case R.id.b_1:
            // act!
            break;

        case R.id.b_2:
            // act!
            break;
    }
}

See that you can use the method actionHandle or any method you define, to handle the click that occur in your botões. If you are going to use the setOnClickListener, would look something like this:

setOnClickListener

public class A extends Activity {

    @Override
    protected void onCreate(Bundle b){
        super.onCreate(b);
        // setContent

        (findViewById(R.id.b_1)).setOnClickListener(actionHandle);
        (findViewById(R.id.b_2)).setOnClickListener(actionHandle);
    }

    View.OnClickListener actionHandle= new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.b_1:

                    break;

                case R.id.b_2:

                    break;
            }
        }
    };
}

In my opinion, use the attribute in XML is more malleable and organized and, of course, if you know how to use the attribute without creating several methods for different buttons, use the android:OnClick is the best option no matter the size of the application.

0

I had the same doubt and I deepened the subject and then of that answer I ended up convincing myself not to use onClick. Basically: the implementations of Android buttons indicate that the button will be clickable, however, if any manufacturer arrow it to false, you will only feel the problem through the market. You can force the button to be clickable, but if you forget, a hug!

EDIT: From what I identified in the answer, the problem is in setting the event Click on a non-button object.

  • If, as it says, "some manufacturer sets it to false" this problem will not have the same effect if using setOnClickListener()?

  • I just did a silly test on an app, I set up my imagebutton with clickable = false and added Onclick, when I click it, I have a runtime error. By keeping clickable as false and using setonClickListener() the image worked normally.

  • I cannot reproduce any error. Both the onClick as setOnClickListener() work. Make sure it’s not the code you put in onClick which causes the error. What has special in the use of android:clickable="false" simultaneously with android:onClick="buttonClick" or setOnClickListener() is that the clickable="false" will have no effect. It is placed in true in the method setOnClickListener().

0

There is no more correct way.

But the second option setOnClickListener in activity is recommended as good practice. For having a faster view of the function that the method has. To perform a maintenance, or even during development, the use of the onClick in XML, may end up generating more confusing code.

  • Can you explain why "recommended as good practice"?

  • @ramaral I edited the answer, but I already had in the answer that is to facilitate the maintenance of the code, because it is easier to visualize. Anyway, thanks for the help.

  • Rereading your answer I get the opposite idea, ie, it seems that when you say "For, for a maintenance, or even during development this ends up generating a more confusing code.", refers to the use of setOnClickListener().

  • Done! I made the correction making it clear that the second option is the best one to be implemented. Again, thank you!

  • On the statement "...the second option is the best one to implement.". Well, that is exactly the purpose of my question, to know what advantage and disadvantage, but you did not indicate any reference. You also said "the second option setOnClickListener in Activity is the recommended..." but recommended by whom?

  • @seamusd In a very large application, it becomes unproductive to maintain these methods, as it is difficult to locate which views this method refers to and vice versa. If the method name is not very explicit that it is an onClick event and is being referenced in an xml layout, or there is no comment specifying this, the programmer may not know this until an error occurs.

  • taken from (http://www.brunonardini.com.br/mobile/android-boas-praticas-para-o-evento-onclick)

  • sorry the link didn’t work link

  • "If the method name is not very explicit ... ", is not a reason not to use, because what is wrong is the name of the method and not the use of onClick. I wish all methods were as easy to name as this.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.