Viewpager+FragmentStatePagerAdapter動態添加,刪除,移動位置,(局部)更新頁面(Fragment)不閃屏,不錯位解決方案

首先固然是引出要解決的需求,在作一個IM模塊時UI是這樣的:上面是水平的聯繫人欄,下面是聊天界面,能夠水平滑動切換聯繫人聊天,也就是說是RecyclerView與Viewpager的聯動,爲了切換時體驗好須要左右兩邊預加載多個聯繫人的聊天內容,用戶收到新消息時當前聊天頁變成第一頁(Viewpager頁面要無閃爍或滑動)頂欄頭像移動到第一個,刪除聊天時移除當前聊天頁其餘緩存的頁不變更,不閃爍,也就是說頁面位置發生變化時已有緩存頁的要用緩存而不是銷燬重建,大致UI請看圖:html

image

簡書上有朋友讓我寫個demo出來給他,這不今天抽時間寫了java

openpageradapter.gif

1. 要實現的幾個功能點:

  • ViewPager中Fragment多少個不固定,須要動態添加,刪除頁面。
  • 更新頁面(Fragment),使用已有的緩存頁面。
  • 移動頁面(Fragment)位置,使用已預加載的緩存頁面。

問題:android

  1. 調用notifyDataSetChanged並無去更新內容。
  2. 添加,刪除,移動頁面後會錯位,position與Fragment對不上。

2. 誤區

在網上搜索會發現,更新ViewPager的方法基本都是說在apdater的getItemPosition()方法裏返回POSITION_NONE,這確實會更新,但也會致使全部頁面被銷燬重建,會出現閃爍等問題,性能上也會不太好。git

3. 原理

要作到動態的更新,添加,刪除ViewPager的數據,咱們須要先弄清ViewPager+adapter是怎麼管理頁面的,首先我假設看此文的你已經熟悉了PagerAdapter的各方法做用,若是沒有的話還請先去查一下,這裏以FragmentStatePagerAdapter爲例,當調用adapter的notifyDataSetChanged後會通知到viewpager檢查更新數據:github

void dataSetChanged() {
  ...
          for (int i = 0; i < mItems.size(); i++) {
          final ItemInfo ii = mItems.get(i);
          final int newPos = mAdapter.getItemPosition(ii.object);

          if (newPos == PagerAdapter.POSITION_UNCHANGED) {
              continue;
          }

          if (newPos == PagerAdapter.POSITION_NONE) {
              mItems.remove(i);
              i--;

              if (!isUpdating) {
                  mAdapter.startUpdate(this);
                  isUpdating = true;
              }

              mAdapter.destroyItem(this, ii.position, ii.object);
              needPopulate = true;

              if (mCurItem == ii.position) {
                  // Keep the current item in the valid range
                  newCurrItem = Math.max(0, Math.min(mCurItem, adapterCount - 1));
                  needPopulate = true;
              }
              continue;
          }

          if (ii.position != newPos) {
              if (ii.position == mCurItem) {
                  // Our current item changed position. Follow it.
                  newCurrItem = newPos;
              }

              ii.position = newPos;
              needPopulate = true;
          }
      }
      ...
      Collections.sort(mItems, COMPARATOR);
  ...
}
...
    static class ItemInfo {
      Object object;
      int position;
      boolean scrolling;
      float widthFactor;
      float offset;
  }
複製代碼

上面是ViewPager dataSetChanged方法裏的一段代碼,能夠看到ViewPager會遍歷它緩存的Item集合,詢問(mAdapter.getItemPosition)Adapter每個Item是刪除了(POSITION_NONE),仍是更新了位置(ii.position != newPos),仍是沒變化(POSITION_UNCHANGED),而後對mItems集合根據新賦值的position進行從新排序。 接下來根據咱們返回的答案進行操做,若是是沒變則不作更改,也就是不會更新內容(PagerAdapter中的getItemPosition默認是直接返回POSITION_NONE,因此調用notifyDataSetChanged默認狀況下是不會更新的),若是是刪除了則從mItems集合中刪除並讓adapter也刪除( mAdapter.destroyItem),若是是更新了位置則根據位置的變化對頁面進行更新,會從新佈局(requestLayout)。而在ViewPaer的onLayout方法裏會遍歷每一個子view而後調用infoForChild()方法從mItems裏找到每一個子view對應的itemInfo:緩存

ItemInfo infoForChild(View child) {
      for (int i = 0; i < mItems.size(); i++) {
          ItemInfo ii = mItems.get(i);
          if (mAdapter.isViewFromObject(child, ii.object)) {
              return ii;
          }
      }
      return null;
  }
複製代碼

看上面代碼咱們知道是經過mAdapter.isViewFromObject()來判斷某個ViewPager的子view到底對應的是哪一個Fragment的rootView的,因此咱們通常在adapter的isViewFromObject方法中會這麼寫:session

public boolean isViewFromObject(View view, Object object) {
      return ((Fragment)object).getView() == view;
  }
複製代碼

這樣就把第幾頁要顯示哪一個fragment的view對應上了,在onlayout時經過子view位置與itemInfo中的offset(至關於偏移到第幾頁)完成了按順序排列頁面。app

從上面的分析咱們知道了adapter的getItemPosition()其實咱們不只僅只能夠返回POSITION_NONE與POSITION_UNCHANGED還能夠根據咱們的須要返回一個更新adapter數據後的新位置ide

總結一下,ViewPager更新過程分爲這幾步:佈局

  1. adapter調用notifyDataSetChanged,ViewPager開始檢測更新.
  2. 經過adapter相應的方法詢問出ViewPager中緩存的頁面在新數據中的更改狀況。
  3. 有更新的話從新調整佈局中View的位置。

4. 處理問題1

弄清理了原理,那麼解決問題1了:咱們須要在Viewpager詢問時告訴ViewPagerItem有哪些變化:

  1. 緩存中某個位置的數據是否與新數據同樣
  2. 緩存老數據在新數據中的位置

處理方式參考了此文:FragmentPagerAdapter 和 FragmentStatePagerAdapter 的數據更新問題

public abstract class FixedPagerAdapter<T> extends FragmentStatePagerAdapter {

    private List<ItemObject> mCurrentItems = new ArrayList<>();

    public FixedPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        while (mCurrentItems.size() <= position) {
            mCurrentItems.add(null);
        }
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        ItemObject object = new ItemObject(fragment, getItemData(position));
        mCurrentItems.set(position, object);
        return object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        mCurrentItems.set(position, null);
        super.destroyItem(container, position, ((ItemObject) object).fragment);
    }

    @Override
    public int getItemPosition(Object object) {
        ItemObject itemObject = (ItemObject) object;
        if (mCurrentItems.contains(itemObject)) {
            T oldData = itemObject.t;
            int oldPosition = mCurrentItems.indexOf(itemObject);
            T newData = getItemData(oldPosition);
            if (equals(oldData, newData)) {
                return POSITION_UNCHANGED;
            } else {
                int newPosition = getDataPosition(oldData);
                return newPosition >= 0 ? newPosition : POSITION_NONE;
            }
        }
        return POSITION_UNCHANGED;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, ((ItemObject) object).fragment);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return super.isViewFromObject(view, ((ItemObject) object).fragment);
    }

    public abstract T getItemData(int position);

    public abstract int getDataPosition(T t);

    public abstract boolean equals(T oldD, T newD);

    public class ItemObject {

        public Fragment fragment;
        public T t;

        public ItemObject(Fragment fragment, T t) {
            this.fragment = fragment;
            this.t = t;
        }
    }

}
複製代碼

在Adapter中對當前ViewPger中緩存的頁面數據進行了保存,而後經過三個抽象方法進行對比:getItemData() ,getDataPosition(),equals(),使用時只須要新建一個Adapter類繼承FixedPagerAdapter完成抽象方法的實現。

這樣作後更新確實沒問題了,比較科學,不會閃爍,所有銷燬,但別忘了咱們還要動態的添加,刪除,移動位置,這時若是隻是這麼處理就會致使頁面錯位問題

緣由就是當你添加,刪除,移動頁面時ViewPager是經過getItemPosition方法對它的緩存集合進行了對應處理,但咱們的FixedPagerAdapter中的緩存並無作刪除,增長位置,排序。

5. 處理問題2

  1. 對FragmentStatePagerAdapter的源碼進行修改,創建一個OpenFragmentStatePagerAdapter類,把原來緩存的Fragment List變成緩存咱們本身的ItemInfo,ItemInfo中保存了3個數據 :fragment,數據和頁面所處的位置。
  2. 在instantiateItem ,destroyItem 時對List中的ItemInfo進行增長,刪除,在getItemPosition時對list中ItemInfo的position按新數據的位置進行賦值。
  3. 在notifyDataSetChanged後和instantiateItem獲取緩存的ItemInfo發現位置不對時進行緩存list的排序,增長等調整。

具體請看代碼,重要位置寫了註釋:

/** * Created by homgwu on 2018/4/2 14:29. */
public abstract class OpenFragmentStatePagerAdapter<T> extends PagerAdapter {
  private static final String TAG = "FragmentStatePagerAdapt";
  private static final boolean DEBUG = false;

  private final FragmentManager mFragmentManager;
  private FragmentTransaction mCurTransaction = null;

  private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();
  private ArrayList<ItemInfo<T>> mItemInfos = new ArrayList();
  private Fragment mCurrentPrimaryItem = null;
  private boolean mNeedProcessCache = false;

  public OpenFragmentStatePagerAdapter(FragmentManager fm) {
      mFragmentManager = fm;
  }

  /** * Return the Fragment associated with a specified position. */
  public abstract Fragment getItem(int position);

  protected Fragment getCachedItem(int position) {
      return mItemInfos.size() > position ? mItemInfos.get(position).fragment : null;
  }

  @Override
  public void startUpdate(ViewGroup container) {
      if (container.getId() == View.NO_ID) {
          throw new IllegalStateException("ViewPager with adapter " + this
                  + " requires a view id");
      }
  }

  @Override
  public Object instantiateItem(ViewGroup container, int position) {
      // If we already have this item instantiated, there is nothing
      // to do. This can happen when we are restoring the entire pager
      // from its saved state, where the fragment manager has already
      // taken care of restoring the fragments we previously had instantiated.
      if (mItemInfos.size() > position) {
          ItemInfo ii = mItemInfos.get(position);
          if (ii != null) {
        //判斷位置是否相等,若是不相等說明新數據有增長或刪除(致使了ViewPager那邊有空位),
              // 而這時notifyDataSetChanged方法尚未完成,ViewPager會先調用instantiateItem來獲取新的頁面
              //因此爲了避免取錯頁面,咱們須要對緩存進行檢查和調整位置:checkProcessCacheChanged
              if (ii.position == position) {
                  return ii;
              } else {
                  checkProcessCacheChanged();
              }
          }
      }

      if (mCurTransaction == null) {
          mCurTransaction = mFragmentManager.beginTransaction();
      }

      Fragment fragment = getItem(position);
      if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
      if (mSavedState.size() > position) {
          Fragment.SavedState fss = mSavedState.get(position);
          if (fss != null) {
              fragment.setInitialSavedState(fss);
          }
      }
      while (mItemInfos.size() <= position) {
          mItemInfos.add(null);
      }
      fragment.setMenuVisibility(false);
      fragment.setUserVisibleHint(false);
      ItemInfo<T> iiNew = new ItemInfo<>(fragment, getItemData(position), position);
      mItemInfos.set(position, iiNew);
      mCurTransaction.add(container.getId(), fragment);

      return iiNew;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {
      ItemInfo ii = (ItemInfo) object;

      if (mCurTransaction == null) {
          mCurTransaction = mFragmentManager.beginTransaction();
      }
      if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
              + " v=" + ((Fragment) object).getView());
      while (mSavedState.size() <= position) {
          mSavedState.add(null);
      }
      mSavedState.set(position, ii.fragment.isAdded()
              ? mFragmentManager.saveFragmentInstanceState(ii.fragment) : null);
      mItemInfos.set(position, null);

      mCurTransaction.remove(ii.fragment);
  }

  @Override
  @SuppressWarnings("ReferenceEquality")
  public void setPrimaryItem(ViewGroup container, int position, Object object) {
      ItemInfo ii = (ItemInfo) object;
      Fragment fragment = ii.fragment;
      if (fragment != mCurrentPrimaryItem) {
          if (mCurrentPrimaryItem != null) {
              mCurrentPrimaryItem.setMenuVisibility(false);
              mCurrentPrimaryItem.setUserVisibleHint(false);
          }
          if (fragment != null) {
              fragment.setMenuVisibility(true);
              fragment.setUserVisibleHint(true);
          }
          mCurrentPrimaryItem = fragment;
      }
  }

  @Override
  public void finishUpdate(ViewGroup container) {
      if (mCurTransaction != null) {
          mCurTransaction.commitNowAllowingStateLoss();
          mCurTransaction = null;
      }
  }

  @Override
  public boolean isViewFromObject(View view, Object object) {
      Fragment fragment = ((ItemInfo) object).fragment;
      return fragment.getView() == view;
  }

  @Override
  public int getItemPosition(Object object) {
      mNeedProcessCache = true;
      ItemInfo<T> itemInfo = (ItemInfo) object;
      int oldPosition = mItemInfos.indexOf(itemInfo);
      if (oldPosition >= 0) {
          T oldData = itemInfo.data;
          T newData = getItemData(oldPosition);
          if (dataEquals(oldData, newData)) {
              return POSITION_UNCHANGED;
          } else {
              ItemInfo<T> oldItemInfo = mItemInfos.get(oldPosition);
              int oldDataNewPosition = getDataPosition(oldData);
              if (oldDataNewPosition < 0) {
                  oldDataNewPosition = POSITION_NONE;
              }
              //把新的位置賦值到緩存的itemInfo中,以便調整時使用
              if (oldItemInfo != null) {
                  oldItemInfo.position = oldDataNewPosition;
              }
              return oldDataNewPosition;
          }

      }

      return POSITION_UNCHANGED;
  }

  @Override
  public void notifyDataSetChanged() {
      super.notifyDataSetChanged();
      //通知ViewPager更新完成後對緩存的ItemInfo List進行調整
      checkProcessCacheChanged();
  }

  private void checkProcessCacheChanged() {
      //只有調用過getItemPosition(也就是有notifyDataSetChanged)才進行緩存的調整
      if (!mNeedProcessCache) return;
      mNeedProcessCache = false;
      ArrayList<ItemInfo<T>> pendingItemInfos = new ArrayList<>(mItemInfos.size());
      //先存入空數據
      for (int i = 0; i < mItemInfos.size(); i++) {
          pendingItemInfos.add(null);
      }
      //根據緩存的itemInfo中的新position把itemInfo入正確的位置
      for (ItemInfo<T> itemInfo : mItemInfos) {
          if (itemInfo != null) {
              if (itemInfo.position >= 0) {
                  while (pendingItemInfos.size() <= itemInfo.position) {
                      pendingItemInfos.add(null);
                  }
                  pendingItemInfos.set(itemInfo.position, itemInfo);
              }
          }
      }
      mItemInfos = pendingItemInfos;
  }

  @Override
  public Parcelable saveState() {
      Bundle state = null;
      if (mSavedState.size() > 0) {
          state = new Bundle();
          Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
          mSavedState.toArray(fss);
          state.putParcelableArray("states", fss);
      }
      for (int i = 0; i < mItemInfos.size(); i++) {
          Fragment f = mItemInfos.get(i).fragment;
          if (f != null && f.isAdded()) {
              if (state == null) {
                  state = new Bundle();
              }
              String key = "f" + i;
              mFragmentManager.putFragment(state, key, f);
          }
      }
      return state;
  }

  @Override
  public void restoreState(Parcelable state, ClassLoader loader) {
      if (state != null) {
          Bundle bundle = (Bundle) state;
          bundle.setClassLoader(loader);
          Parcelable[] fss = bundle.getParcelableArray("states");
          mSavedState.clear();
          mItemInfos.clear();
          if (fss != null) {
              for (int i = 0; i < fss.length; i++) {
                  mSavedState.add((Fragment.SavedState) fss[i]);
              }
          }
          Iterable<String> keys = bundle.keySet();
          for (String key : keys) {
              if (key.startsWith("f")) {
                  int index = Integer.parseInt(key.substring(1));
                  Fragment f = mFragmentManager.getFragment(bundle, key);
                  if (f != null) {
                      while (mItemInfos.size() <= index) {
                          mItemInfos.add(null);
                      }
                      f.setMenuVisibility(false);
                      ItemInfo<T> iiNew = new ItemInfo<>(f, getItemData(index), index);
                      mItemInfos.set(index, iiNew);
                  } else {
                      Log.w(TAG, "Bad fragment at key " + key);
                  }
              }
          }
      }
  }

  protected Fragment getCurrentPrimaryItem() {
      return mCurrentPrimaryItem;
  }

  protected Fragment getFragmentByPosition(int position) {
      if (position < 0 || position >= mItemInfos.size()) return null;
      return mItemInfos.get(position).fragment;
  }

  abstract T getItemData(int position);

  abstract boolean dataEquals(T oldData, T newData);

  abstract int getDataPosition(T data);

  static class ItemInfo<D> {
      Fragment fragment;
      D data;
      int position;

      public ItemInfo(Fragment fragment, D data, int position) {
          this.fragment = fragment;
          this.data = data;
          this.position = position;
      }
  }
}
複製代碼

這個是抽象的基類,而後咱們在具體業務代碼處寫一個Adapter繼承OpenFragmentStatePagerAdapter,就能夠用極少的代碼來使用了,當須要更新某個具體的頁面時不須要notifyDataSetChanged,只須要用getFragmentByPosition來取出具體頁面,而後局部更新內容

使用(由於項目中是kotlin寫的,後面有朋友要demo時寫了個java版在文章最後的github地址中):

/** * Created by homgwu on 2018/3/23 10:12. */
class ListChatViewPagerAdapter(fragmentManager: FragmentManager, val viewPager: ViewPager) : OpenFragmentStatePagerAdapter<SessionItem>(fragmentManager), AnkoLogger {
   private var mData: ArrayList<SessionItem> = ArrayList()

   constructor(fragmentManager: FragmentManager, viewPager: ViewPager, data: List<SessionItem>?) : this(fragmentManager, viewPager) {
       mData.clear()
       if (data != null) mData.addAll(data)
   }

   override fun getItem(position: Int): Fragment {
       info {
           "getItem position=$position"
       }
       return ChatListFragment.newInstance(mData[position].data, ChatListFragment.COME_FROM_LIST_CHAT)
   }

   override fun getCount(): Int {
       info {
           "getCount count=${mData.size}"
       }
       return mData.size
   }

// override fun getItemPosition(`object`: Any?): Int {
//// return findItemPosition(`object` as ChatListFragment)
// return POSITION_NONE
// }

   fun getCurrentFragmentItem(): ChatListFragment? {
       return getCurrentPrimaryItem() as? ChatListFragment
   }

   fun setNewData(data: List<SessionItem>) {
       mData.clear()
       mData.addAll(data)
       notifyDataSetChanged()
   }

   fun addData(sessionItem: SessionItem) {
       mData.add(sessionItem)
       notifyDataSetChanged()
   }

   fun addData(position: Int, sessionItem: SessionItem) {
       mData.add(position, sessionItem)
       notifyDataSetChanged()
   }

   fun remove(position: Int) {
       mData.removeAt(position)
       notifyDataSetChanged()
   }

   fun moveData(from: Int, to: Int) {
       if (from == to) return
       Collections.swap(mData, from, to)
// updateByPosition(from, mData[from])
// updateByPosition(to, mData[to])
       notifyDataSetChanged()
   }

   fun moveDataToFirst(from: Int) {
       val tempData = mData.removeAt(from)
       mData.add(0, tempData)
       notifyDataSetChanged()
   }

   fun updateByPosition(position: Int, sessionItem: SessionItem) {
       if (position >= 0 && mData.size > position) {
           mData[position] = sessionItem
           var targetF = getCachedFragmentByPosition(position)
           if (targetF != null) {
               targetF.resetData(sessionItem.data)
           }
       }
   }

   override fun getItemData(position: Int): SessionItem? {
       return if (mData.size > position) mData[position] else null
   }

   override fun dataEquals(oldData: SessionItem?, newData: SessionItem?): Boolean {
       return oldData == newData
   }

   override fun getDataPosition(data: SessionItem?): Int {
       return if (data == null) -1 else mData.indexOf(data)
   }

   fun getCachedFragmentByPosition(position: Int): ChatListFragment? {
       return getFragmentByPosition(position) as? ChatListFragment
   }

}
複製代碼

Kotlin版OpenFragmentStatePagerAdapter:

/** * Created by homgwu on 2018/3/23 09:35. */
abstract class OpenFragmentStatePagerAdapter<T>(private val mFragmentManager: FragmentManager) : PagerAdapter() {

   private val TAG = "FragmentStatePagerAdapt"
   private val DEBUG = false

   private var mCurTransaction: FragmentTransaction? = null

   private val mSavedState = ArrayList<Fragment.SavedState?>()
   private var mItemInfos = ArrayList<ItemInfo<T>?>()
   protected var mCurrentPrimaryItem: Fragment? = null
   private var mNeedProcessCache = false

   /** * Return the Fragment associated with a specified position. */
   abstract fun getItem(position: Int): Fragment

   protected fun getCachedItem(position: Int): Fragment? = if (mItemInfos.size > position) mItemInfos[position]?.fragment else null

   override fun startUpdate(container: ViewGroup) {
       if (container.id == View.NO_ID) {
           throw IllegalStateException("ViewPager with adapter " + this
                   + " requires a view id")
       }
   }

   override fun instantiateItem(container: ViewGroup, position: Int): Any {
       // If we already have this item instantiated, there is nothing
       // to do. This can happen when we are restoring the entire pager
       // from its saved state, where the fragment manager has already
       // taken care of restoring the fragments we previously had instantiated.
       if (mItemInfos.size > position) {
           val ii = mItemInfos[position]
           ii?.let {
               if (it.position == position) {
                   return this
               } else {
                   checkProcessCacheChanged()
               }
           }
       }

       val fragment = getItem(position)
       if (DEBUG) Log.v(TAG, "Adding item #$position: f=$fragment")
       if (mSavedState.size > position) {
           val fss = mSavedState[position]
           if (fss != null) {
               fragment.setInitialSavedState(fss)
           }
       }
       while (mItemInfos.size <= position) {
           mItemInfos.add(null)
       }
       fragment.setMenuVisibility(false)
       fragment.userVisibleHint = false
       val iiNew = ItemInfo(fragment, getItemData(position), position)
       mItemInfos[position] = iiNew
       if (mCurTransaction == null) {
           mCurTransaction = mFragmentManager.beginTransaction()
       }
       mCurTransaction!!.add(container.id, fragment)

       return iiNew
   }

   override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
       val ii = `object` as ItemInfo<T>

       if (DEBUG)
           Log.v(TAG, "Removing item #" + position + ": f=" + `object`
                   + " v=" + ii.fragment.view)
       while (mSavedState.size <= position) {
           mSavedState.add(null)
       }
       mSavedState[position] = if (ii.fragment.isAdded)
           mFragmentManager.saveFragmentInstanceState(ii.fragment)
       else
           null
       mItemInfos[position] = null
       if (mCurTransaction == null) {
           mCurTransaction = mFragmentManager.beginTransaction()
       }
       mCurTransaction!!.remove(ii.fragment)
   }

   override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any?) {
       val ii = `object` as? ItemInfo<T>
       val fragment = ii?.fragment
       if (fragment != mCurrentPrimaryItem) {
           mCurrentPrimaryItem?.apply {
               setMenuVisibility(false)
               userVisibleHint = false
           }
           fragment?.apply {
               setMenuVisibility(true)
               userVisibleHint = true
           }
           mCurrentPrimaryItem = fragment
       }
   }

   override fun finishUpdate(container: ViewGroup) {
       mCurTransaction?.apply {
           commitNowAllowingStateLoss()
       }
       mCurTransaction = null
   }

   override fun isViewFromObject(view: View, `object`: Any): Boolean {
       val fragment = (`object` as ItemInfo<T>).fragment
       return fragment.view === view
   }

   override fun getItemPosition(`object`: Any?): Int {
       mNeedProcessCache = true
       val itemInfo: ItemInfo<T> = `object` as ItemInfo<T>
       val oldPosition = mItemInfos.indexOf(itemInfo)
       if (oldPosition >= 0) {
           val oldData: T? = itemInfo.data
           val newData: T? = getItemData(oldPosition)
           return if (dataEquals(oldData, newData)) {
               PagerAdapter.POSITION_UNCHANGED
           } else {
               val oldItemInfo = mItemInfos[oldPosition]
               var oldDataNewPosition = getDataPosition(oldData)
               if (oldDataNewPosition < 0) {
                   oldDataNewPosition = PagerAdapter.POSITION_NONE
               }
               oldItemInfo?.apply {
                   position = oldDataNewPosition
               }
               oldDataNewPosition
           }
       }
       return PagerAdapter.POSITION_UNCHANGED
   }

   override fun notifyDataSetChanged() {
       super.notifyDataSetChanged()
       checkProcessCacheChanged()
   }

   private fun checkProcessCacheChanged() {
       if (!mNeedProcessCache) return
       mNeedProcessCache = false
       val pendingItemInfos = ArrayList<ItemInfo<T>?>(mItemInfos.size)
       for (i in 0..(mItemInfos.size - 1)) {
           pendingItemInfos.add(null)
       }
       for (value in mItemInfos) {
           value?.apply {
               if (position >= 0) {
                   while (pendingItemInfos.size <= position) {
                       pendingItemInfos.add(null)
                   }
                   pendingItemInfos[value.position] = value
               }
           }
       }
       mItemInfos = pendingItemInfos
   }

   override fun saveState(): Parcelable? {
       var state: Bundle? = null
       if (mSavedState.size > 0) {
           state = Bundle()
           val fss = arrayOfNulls<Fragment.SavedState>(mSavedState.size)
           mSavedState.toArray(fss)
           state.putParcelableArray("states", fss)
       }
       for (i in mItemInfos.indices) {
           val f = mItemInfos[i]?.fragment
           if (f != null && f.isAdded) {
               if (state == null) {
                   state = Bundle()
               }
               val key = "f$i"
               mFragmentManager.putFragment(state, key, f)
           }
       }
       return state
   }

   override fun restoreState(state: Parcelable?, loader: ClassLoader?) {
       if (state != null) {
           val bundle = state as Bundle?
           bundle!!.classLoader = loader
           val fss = bundle.getParcelableArray("states")
           mSavedState.clear()
           mItemInfos.clear()
           if (fss != null) {
               for (i in fss.indices) {
                   mSavedState.add(fss[i] as Fragment.SavedState)
               }
           }
           val keys = bundle.keySet()
           for (key in keys) {
               if (key.startsWith("f")) {
                   val index = Integer.parseInt(key.substring(1))
                   val f = mFragmentManager.getFragment(bundle, key)
                   if (f != null) {
                       while (mItemInfos.size <= index) {
                           mItemInfos.add(null)
                       }
                       f.setMenuVisibility(false)
                       val iiNew = ItemInfo(f, getItemData(index), index)
                       mItemInfos[index] = iiNew
                   } else {
                       Log.w(TAG, "Bad fragment at key $key")
                   }
               }
           }
       }
   }

   protected fun getCurrentPrimaryItem() = mCurrentPrimaryItem
   protected fun getFragmentByPosition(position: Int): Fragment? {
       if (position < 0 || position >= mItemInfos.size) return null
       return mItemInfos[position]?.fragment
   }

   abstract fun getItemData(position: Int): T?

   abstract fun dataEquals(oldData: T?, newData: T?): Boolean

   abstract fun getDataPosition(data: T?): Int

   class ItemInfo<D>(var fragment: Fragment, var data: D?, var position: Int)
}

複製代碼

到此,咱們已經能夠愉快的使用ViewPager+OpenFragmentStatePagerAdapter來動態添加,刪除,移動位置,更新或局部更新頁面了。源碼及Demo 在下面的github地址中。

做者:竹塵居士 GitHub:https://github.com/homgwu/OpenPagerAdapter 博客:http://zhuchen.vip/2018/04/04/android/android-viewpager-adapter-update-move-add.html

相關文章
相關標籤/搜索