How to handle button clicks using the XML onClick within Fragments

前端 未结 18 1544
旧时难觅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 01:59

    Adding to Blundell's answer,
    If you have more fragments, with plenty of onClicks:

    Activity:

    Fragment someFragment1 = (Fragment)getFragmentManager().findFragmentByTag("someFragment1 "); 
    Fragment someFragment2 = (Fragment)getFragmentManager().findFragmentByTag("someFragment2 "); 
    Fragment someFragment3 = (Fragment)getFragmentManager().findFragmentByTag("someFragment3 "); 
    
    ...onCreate etc instantiating your fragments
    
    public void myClickMethod(View v){
      if (someFragment1.isVisible()) {
           someFragment1.myClickMethod(v);
      }else if(someFragment2.isVisible()){
           someFragment2.myClickMethod(v);
      }else if(someFragment3.isVisible()){
           someFragment3.myClickMethod(v); 
      }
    
    } 
    

    In Your Fragment:

      public void myClickMethod(View v){
         switch(v.getid()){
           // Just like you were doing
         }
      } 
    

提交回复
热议问题