ViewPager+PagerAdapter局部刷新
ViewPager如果想要刷新页面,按照正常的操作,直接调用adapter 的notifyDataSetChanged方法,结果发现并没有刷新;
经过查看了notifyDataSetChanged方法源码,发现了一处代码能说明为什么没有更新
for (int i = 0; i < mItems.size(); i++) {
final ItemInfo ii = mItems.get(i);
//获取View的状态
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;
}
从上面代码可以看出ViewPager是否刷新的关键在PagerAdapter的getItemPosition中返回的状态,根据官方API
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 or POSITION_NONE if the item is no longer present in the adapter.
当返回POSITION_UNCHANGED时不会更新页面布局,返回POSITION_NONE重新刷新页面
@Override
public int getItemPosition(@NonNull Object object) {
//强制刷新所有页面
return POSITION_NONE;
}
但有时候只需要做局部刷新时,比如只刷新当前显示的页面,这时候只需要重写setPrimaryItem(),获取当前View
@Override
public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
mCurrentView= (View) object;
super.setPrimaryItem(container, position, object);
}
然后在getItemPosition()判断要刷新的View是否为当前的View,返回相应的状态即可
@Override
public int getItemPosition(@NonNull Object object) {
if (mCurrentView==object) {
return POSITION_NONE;
}else{
return POSITION_UNCHANGED;
}
}