How exactly does the android:onClick XML attribute differ from setOnClickListener?

后端 未结 17 2145
野趣味
野趣味 2020-11-21 11:50

From that I\'ve read you can assign a onClick handler to a button in two ways.

Using the android:onClick XML attribute where you just use t

17条回答
  •  情话喂你
    2020-11-21 12:14

    Another way to set your on click listeners would be to use XML. Just add android:onClick attribute to your tag.

    It is a good practice to use the xml attribute “onClick” over an anonymous Java class whenever possible.

    First of all, lets have a look at the difference in code:

    XML Attribute / onClick attribute

    XML portion

    Java portion

    public void showToast(View v) {
        //Add some logic
    }
    

    Anonymous Java Class / setOnClickListener

    XML Portion

    Java portion

    findViewById(R.id.button1).setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Add some logic
            }
    });
    

    Here are the benefits of using the XML attribute over an anonymous Java class:

    • With Anonymous Java class we always have to specify an id for our elements, but with XML attribute id can be omitted.
    • With Anonymous Java class we have to actively search for the element inside of the view (findViewById portion), but with the XML attribute Android does it for us.
    • Anonymous Java class requires at least 5 lines of code, as we can see, but with the XML attribute 3 lines of code is sufficient.
    • With Anonymous Java class we have to name of our method “onClick", but with the XML attribute we can add any name we want, which will dramatically help with the readability of our code.
    • Xml “onClick” attribute has been added by Google during the API level 4 release, which means that it is a bit more modern syntax and modern syntax is almost always better.

    Of course, it is not always possible to use the Xml attribute, here are the reasons why we wouldn’t chose it:

    • If we are working with fragments. onClick attribute can only be added to an activity, so if we have a fragment, we would have to use an anonymous class.
    • If we would like to move the onClick listener to a separate class (maybe if it is very complicated and/or we would like to re-use it in different parts of our application), then we wouldn’t want to use the xml attribute either.

提交回复
热议问题