Android中ViewPager你所不知道的优化技巧分享

  void dataSetChanged() {

  // This method only gets called if our observer is attached, so mAdapter is non-null.

  final int adapterCount = mAdapter.getCount();

  mExpectedAdapterCount = adapterCount;

  boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1

  && mItems.size() < adapterCount;

  int newCurrItem = mCurItem;

  boolean isUpdating = false;

  //mItems为旧数据的容器

  for (int i = 0; i < mItems.size(); i++) {

  final ItemInfo ii = mItems.get(i);

  //返回刷新之前Tab项所处的位置

  final int newPos = mAdapter.getItemPosition(ii.object);

  //返回的位置等于POSITION_UNCHANGED(-1)表示当前页未有变更,不做任何操作

  if (newPos == PagerAdapter.POSITION_UNCHANGED) {

  continue;

  }

  //如果返回的位置等于POSITION_NONE(-2)表示当前页Tab项刷新后不存在,需要销毁并重新加载新的页面

  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) {

  //这段代码是将页面定位到刷新之前的打开页,据数据的position和mCurItem相等的话,则表示这个item是之前打开的,赋予它新位置的值

  if (ii.position == mCurItem) {

  // Our current item changed position. Follow it.

  newCurrItem = newPos;

  }

  ii.position = newPos;

  needPopulate = true;

  }

  }

  if (isUpdating) {

  mAdapter.finishUpdate(this);

  }

  Collections.sort(mItems, COMPARATOR);

  if (needPopulate) {

  // Reset our known page widths; populate will recompute them.

  final int childCount = getChildCount();

  for (int i = 0; i < childCount; i++) {

  final View child = getChildAt(i);

  final LayoutParams lp = (LayoutParams) child.getLayoutParams();

  if (!lp.isDecor) {

  lp.widthFactor = 0.f;

  }

  }

  setCurrentItemInternal(newCurrItem, false, true);

  requestLayout();

  }

  }