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

后端 未结 17 2109
野趣味
野趣味 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:24

    By using the XML attribute you just need to define a method instead of a class so I was wondering if the same can be done via code and not in the XML layout.

    Yes, You can make your fragment or activity implement View.OnClickListener

    and when you initialize your new view objects in code you can simply do mView.setOnClickListener(this);

    and this automatically sets all view objects in code to use the onClick(View v) method that your fragment or activity etc has.

    to distinguish which view has called the onClick method, you can use a switch statement on the v.getId() method.

    This answer is different from the one that says "No that is not possible via code"

    0 讨论(0)
  • 2020-11-21 12:24

    Supporting Ruivo's answer, yes you have to declare method as "public" to be able to use in Android's XML onclick - I am developing an app targeting from API Level 8 (minSdk...) to 16 (targetSdk...).

    I was declaring my method as private and it caused error, just declaring it as public works great.

    0 讨论(0)
  • 2020-11-21 12:24

    The best way to do this is with the following code:

     Button button = (Button)findViewById(R.id.btn_register);
     button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //do your fancy method
                }
            });
    
    0 讨论(0)
  • 2020-11-21 12:25

    When I saw the top answer, it made me realize that my problem was not putting the parameter (View v) on the fancy method:

    public void myFancyMethod(View v) {}
    

    When trying to access it from the xml, one should use

    android:onClick="myFancyMethod"/>
    

    Hope that helps someone.

    0 讨论(0)
  • 2020-11-21 12:27

    There are very well answers here, but I want to add one line:

    In android:onclick in XML, Android uses java reflection behind the scene to handle this.

    And as explained here, reflection always slows down the performance. (especially on Dalvik VM). Registering onClickListener is a better way.

    0 讨论(0)
提交回复
热议问题