How to instantiate fragment class using class name instead of index

后端 未结 3 1249
无人及你
无人及你 2021-02-20 05:41

I have two fragment class named SessionTab and BillingTaband i am trying to create instance of those class using

SessionTab sessionTab          


        
3条回答
  •  半阙折子戏
    2021-02-20 06:25

    First of all, if you should understand that instance for any Fragment you can take from Java class api. Like below:

    Class class = Class.forName("example.package.BillingFragment");
    Constructor cons = class.getConstructor(BillingFragment.class);
    BillingFragment object = (BillingFragment) cons.newInstance();
    

    Code example show, how get Instance from any class in Java. But you talking a little bit other things. If I understand correct, you want to get Fragment from FragmentManager.

    You can do it, in case if you already defined Fragment before! For example, you have base application flow, and then you want added Fragment. You can check FragmentManager if there are Fragments in stack. But in case of empty stack, you should manually add them:

    String billingFragmentTag = BillingFragment.class.getSimpleName();
    
    ......
    
    if (getFragmentManager.findFragmentByTag(billingFragmentTag) == null) {
      BillingFragment fragment = new BillingFragment();
      String billingFragmentTag = BillingFragment.class.getSimpleName();
    
      FragmentTransaction fragTrans = getFragmentManager().beginTransaction();
               fragTrans.add(fragment, billingFragmentTag).commit();
    }
    
    ......
    

    So after this, you can check if there your Fragment in stack and hook this active instance. This is correct and standard flow for using Fragments.

    ......
    
    if (getFragmentManager.findFragmentByTag(billingFragmentTag) != null) {
      BillingFragment fragment = getFragmentManager.findFragmentByTag(billingFragmentTag);
      String billingFragmentTag = BillingFragment.class.getSimpleName();
    
      FragmentTransaction fragTrans = getFragmentManager().beginTransaction();
               fragTrans.add(fragment, billingFragmentTag).commit();
    }
    
    ....
    

    Welcome!

提交回复
热议问题