當(dāng)Viewpager設(shè)置了pageTransformer,在執(zhí)行notifyDataSetChanged后寺谤,所設(shè)置的PageTransformer會(huì)失效。
網(wǎng)上找到的解決方法為notifyDataSetChanged前重新設(shè)置adapter或者notifyDataSetChanged后執(zhí)行setCurrentItem吮播。但是效果不是太好变屁。
最后進(jìn)入ViewPager源碼發(fā)現(xiàn)只有一處會(huì)執(zhí)行PageTransformer的回調(diào)。
protected void onPageScrolled(int position, float offset, int offsetPixels) {
//省略其他代碼
if (mPageTransformer != null) {
final int scrollX = getScrollX();
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) continue;
final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth();
mPageTransformer.transformPage(child, transformPos);
}
}
}
通過打斷點(diǎn)發(fā)現(xiàn)意狠,是因?yàn)閏hild.getLeft()為0導(dǎo)致的PageTransformer顯示異常粟关。
child.getLeft()為0可通過child.post解決,把代碼復(fù)制出來稍作修改环戈,放在notifyDataSetChanged后執(zhí)行
listData.clear();
listData.addAll(data);
adapter.notifyDataSetChanged();
//mPageTransformer為viewpager設(shè)置的PageTransformer
if (mPageTransformer != null) {
final int scrollX = viewpager.getScrollX();
final int childCount = viewpager.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = viewpager.getChildAt(i);
final ViewPager.LayoutParams lp = (ViewPager.LayoutParams) child.getLayoutParams();
if (lp.isDecor) continue;
int clientWidth = viewpager.getMeasuredWidth() - viewpager.getPaddingLeft() - viewpager.getPaddingRight();
child.post(new Runnable() {
@Override
public void run() {
final float transformPos = (float) (child.getLeft() - scrollX) / clientWidth;
mPageTransformer.transformPage(child, transformPos);
}
});
}
}
最終效果在notifyDataSetChanged后還是會(huì)有一瞬間的閃動(dòng)闷板,因?yàn)閏hild.post回調(diào)需要一定的時(shí)間。
如果介意的話可以自己手動(dòng)去計(jì)算child.left的位置解決院塞。具體方法就不細(xì)說了