Android FragmentStatePagerAdapter, how to tag a fragment to find it later

前端 未结 9 1196
独厮守ぢ
独厮守ぢ 2020-12-24 14:09

When using the FragmentStatePageAdapter I get the fragments like this:

    @Override
    public Fragment getItem(int position) {
        return          


        
相关标签:
9条回答
  • 2020-12-24 14:59

    I've found another way of doing it, not sure if there would be any issues for using it, it seems ok to me.

    I was checking at the code for FragmentStatePageAdapter and I saw this method:

    @Override
    52     public Object More ...instantiateItem(View container, int position) {
    53         // If we already have this item instantiated, there is nothing
    54         // to do.  This can happen when we are restoring the entire pager
    55         // from its saved state, where the fragment manager has already
    56         // taken care of restoring the fragments we previously had instantiated.
    57         if (mFragments.size() > position) {
    58             Fragment f = mFragments.get(position);
    59             if (f != null) {
    60                 return f;
    61             }
    62         }
    63 
    64         if (mCurTransaction == null) {
    65             mCurTransaction = mFragmentManager.beginTransaction();
    66         }
    67 
    68         Fragment fragment = getItem(position);
    69         if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
    70         if (mSavedState.size() > position) {
    71             Fragment.SavedState fss = mSavedState.get(position);
    72             if (fss != null) {
    73                 fragment.setInitialSavedState(fss);
    74             }
    75         }
    76         while (mFragments.size() <= position) {
    77             mFragments.add(null);
    78         }
    79         fragment.setMenuVisibility(false);
    80         mFragments.set(position, fragment);
    81         mCurTransaction.add(container.getId(), fragment);
    82 
    83         return fragment;
    84     }
    

    You can use this method to get the fragment already instated for that particular position. So if you want to get Fragment at position 1, you just need to call:

    myFragmentStatePageAdpater.instantiateItem(null, 1)
    

    Hope that helps

    0 讨论(0)
  • 2020-12-24 15:00

    Solution with storing fragments to a HashMap in your getItem() method does not work if your activity is re-created!

    Problem is, default implementation of the FragmentStatePagerAdapter restores fragments directly from the FragmentManager without calling the getItem() method. This means that you'll never get a chance to store a reference to your fragment.

    For more info, see source code: FragmentStatePagerAdapter#restoreState.

    This basically means that the only way to get a reference to your fragment is by resorting to reflections. This is relatively* safe** in case youre using support library.

    Here's how:

        @SuppressWarnings("unchecked")
        public Fragment getFragment(int position) {
            try {
                Field f = FragmentStatePagerAdapter.class.getDeclaredField("mFragments");
                f.setAccessible(true);
                ArrayList<Fragment> fragments = (ArrayList<Fragment>) f.get(this);
                if (fragments.size() > position) {
                    return fragments.get(position);
                }
                return null;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    

    relatively* means that its not as dangerous as using reflection on framework classes. Support classes are compiled into your app and there is no way that this code will work on your device but will crash on some other device. You can still potentially break this solution by updating support library to a newer version

    safe** its never really safe to use reflections; however you have to resort to this method when a library you're using has design flaws.

    0 讨论(0)
  • 2020-12-24 15:04

    As @Lancelot mentioned, You may just call and cast result to your SuperCoolFragment:

    SuperCoolFragment frag = (SuperCoolFragment) yourFragmentStatePageAdpater.instantiateItem(null, position); 
    
    0 讨论(0)
提交回复
热议问题