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

前端 未结 9 1240
独厮守ぢ
独厮守ぢ 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

提交回复
热议问题