ViewPager中调用notifyDataSetChanged无刷新最终方案.

时间:2022-12-20 17:55:09

通过查找文献和阅读代码发现:  mViewpager.getAdapter.notifyDataSetChanged(); 一直返回POSITION_UNCHANGED. 默认pisition无变化即不刷新.  如果想viewpager在数据变化时候刷新,就需要让itemPosition 返回POSITION_NONE.  但是如果我们不对返回的条件进行判断.就会导致viewpager所有页面都会在调用 mViewpager.getAdapter.notifyDataSetChanged();  强行刷新.  非常消耗内存和电量. 



以下是源码和文献:


 查看方法 super.notifyDataSetChanged()调用的是PagerAdapter.notifyDataSetChanged()  /**     * This method should be called by the application if the data backing this adapter has changed     * and associated views should update.     */    public void notifyDataSetChanged() {        mObservable.notifyChanged();    } 注释里说到,当附加在适配器上的数据发生变化时,应该调用该方法刷新数据。该方法调用了一个mObservable .notifyChanged(); 我们继续跟进这个方法,进入DataSetObservable类中,发现这样一段代码: /**     * Invokes {@link DataSetObserver#onChanged} on each observer.     * Called when the contents of the data set have changed.  The recipient     * will obtain the new contents the next time it queries the data set.     */    public void notifyChanged() {        synchronized(mObservers ) {            // since onChanged() is implemented by the app, it could do anything, including            // removing itself from {@link mObservers} - and that could cause problems if            // an iterator is used on the ArrayList {@link mObservers}.            // to avoid such problems, just march thru the list in the reverse order.            for (int i = mObservers .size() - 1; i >= 0; i--) {                mObservers.get(i).onChanged();            }        }    } 这都不是重点,重点我们来看这个mObservers的类型是一个抽象类DataSetObserver,里面只有两个未实现的方法,都有谁使用了这个抽象类呢,其中我们发现了Viewpager的身影。进入viewpager,我们终于找到了viewpager中控制数据变更的重点方法dataSetChanged ,这个方法如下:  void dataSetChanged () {        // This method only gets called if our observer is attached, so mAdapter is non-null.         boolean needPopulate = mItems .size() < mOffscreenPageLimit * 2 + 1 &&                mItems.size() < mAdapter.getCount();        int newCurrItem = mCurItem ;         boolean isUpdating = false;        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, mAdapter.getCount() - 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;            }        }         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();        }    } 重点看这样一行代码: final int newPos = mAdapter.getItemPosition(ii.object );    if (newPos == PagerAdapter.POSITION_UNCHANGED ) {         continue ;   }  Called when the host view is attempting to determine if an item’s position has changed. Returns POSITION_UNCHANGED if the position of the given item has not changed orPOSITION_NONE if the item is no longer present in the adapter. The default implementation assumes that items will never change position and always returnsPOSITION_UNCHANGED. 意思是如果item的位置如果没有发生变化,则返回POSITION_UNCHANGED。如果返回了POSITION_NONE,表示该位置的item已经不存在了。默认的实现是假设item的位置永远不会发生变化,而返回POSITION_UNCHANGED


在fragmentpageradapter中 可以对每一个object(实际上就是fragment)判断 他和当前页面的fragment是否属于同一个类,即是否属于同一个fragment来判断是否刷新该页面.

mViewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

Fragment mCurrentFragment;

@Override
public Fragment getItem(int position) {
return mIModel.getMainFragment(position);
}

@Override
public int getCount() {
return mTitles.length;
}

@Override
public CharSequence getPageTitle(int position) {
return mTitles[position];
}

@Override
public int getItemPosition(Object object) {
Fragment preFragment = (Fragment) object; //每个fragment


if (preFragment.getClass() == mCurrentView.getClass()) {



return POSITION_NONE;
} else {
return POSITION_UNCHANGED;
}


}

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
mCurrentFragment= (Fragment) object; //当前页面的fragmentg
super.setPrimaryItem(container, posi tion, object);

}


});