相信用过viewpager的同学都会遇到调用notifydataSetChanged()后不刷新或者不符合预期的问题,今天就来分析分析这里的来龙去脉。这一切还得从viewpager的setAdapter说起:
/**
* Set a PagerAdapter that will supply views for this pager as needed.
*
* @param adapter Adapter to use
*/
public void setAdapter(PagerAdapter adapter) {
...(省略若干行,下同)
...
final PagerAdapter oldAdapter = mAdapter;
mAdapter = adapter;
mExpectedAdapterCount = 0;
if (mAdapter != null) {
if (mObserver == null) {
mObserver = new PagerObserver();
}
mAdapter.registerDataSetObserver(mObserver);
...
...
}
...
}
mAdapter.registerDataSetObserver(mObserver)这里用到了观察者模式,mObserver是PagerObserver的一个实例,而PagerObserver是ViewPager的一个内部类,其声明如下:
private class PagerObserver extends DataSetObserver {
@Override
public void onChanged() {
//这里调用了viewpager的dataSetChanged()方法,下同
dataSetChanged();
}
@Override
public void onInvalidated() {
dataSetChanged();
}
}