ViewPager的PagerAdapter中的notifyDataSetChanged时,页面数据不更新问题

ViewPager中调用PagerAdapter.notifydatasetchanged方法时候页面没有任何刷新效果;

查阅官方API是这样解释的:大概是说明Adapter会自动管辖ViewPager每一页(Item)的状态,而notifyDataSetChanged()是用在当ViePager要新增一页、刪除一页或改变各个页面的排列的時候。

所以ViewPager Adapter的notifyDataSetChanged自然就不适用于只更新ViewPager里面某个View的內容的需求。

解决方案:

重写 PagerAdapter 的 getItemPosition() 方法,并返回 POSITION_NONE ,以触发 PagerAdapter 销毁并重建对象。

@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}

 

进入ViewPager代码发现:

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);
//根据getItemPosition的返回值,来决定是否调用destroyItem方法。
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();
}
}

 

从源码上面可以看到,它会判断adapter的getItemPosition方法的返回值,只有当返回值是POSITION_NONE时候,才会调用item的remove方法以及startUpdate和destroyItem方法,进而去更新数据。默认返回值是POSITION_UNCHANGED,不执行任何操作。

PagerAdapter 的 getItemPosition() 方法的默认实现:

public int getItemPosition(Object object) {
return POSITION_UNCHANGED;
}

 

转载于:https://www.cnblogs.com/oceanfhy/p/7227876.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值