How to handle button clicks using the XML onClick within Fragments

前端 未结 18 1516
旧时难觅i
旧时难觅i 2020-11-22 01:41

Pre-Honeycomb (Android 3), each Activity was registered to handle button clicks via the onClick tag in a Layout\'s XML:

android:onClick=\"m         


        
18条回答
  •  长情又很酷
    2020-11-22 02:01

    I would rather go for the click handling in code than using the onClick attribute in XML when working with fragments.

    This becomes even easier when migrating your activities to fragments. You can just call the click handler (previously set to android:onClick in XML) directly from each case block.

    findViewById(R.id.button_login).setOnClickListener(clickListener);
    ...
    
    OnClickListener clickListener = new OnClickListener() {
        @Override
        public void onClick(final View v) {
            switch(v.getId()) {
               case R.id.button_login:
                  // Which is supposed to be called automatically in your
                  // activity, which has now changed to a fragment.
                  onLoginClick(v);
                  break;
    
               case R.id.button_logout:
                  ...
            }
        }
    }
    

    When it comes to handling clicks in fragments, this looks simpler to me than android:onClick.

提交回复
热议问题