ViewPager and fragments — what's the right way to store fragment's state?

后端 未结 11 1341
遇见更好的自我
遇见更好的自我 2020-11-22 02:21

Fragments seem to be very nice for separation of UI logic into some modules. But along with ViewPager its lifecycle is still misty to me. So Guru thoughts are b

11条回答
  •  囚心锁ツ
    2020-11-22 02:51

    A bit different opinion instead of storing the Fragments yourself just leave it to the FragmentManager and when you need to do something with the fragments look for them in the FragmentManager:

    //make sure you have the right FragmentManager 
    //getSupportFragmentManager or getChildFragmentManager depending on what you are using to manage this stack of fragments
    List fragments = fragmentManager.getFragments();
    if(fragments != null) {
       int count = fragments.size();
       for (int x = 0; x < count; x++) {
           Fragment fragment = fragments.get(x);
           //check if this is the fragment we want, 
           //it may be some other inspection, tag etc.
           if (fragment instanceof MyFragment) {
               //do whatever we need to do with it
           }
       }
    }
    

    If you have a lot of Fragments and the cost of instanceof check may be not what you want, but it is good thing to have in mind that the FragmentManager already keeps account of Fragments.

提交回复
热议问题