Android学习笔记——关于Android ViewPager 在 adapter.notifyDataSetChanged 后 setCurrentItem 方法失效的解决办法

   今天遇到了一个项目上的bug,就是在使用 ViewPager 连接 多个 Fragment 做切换时,ViewPager 的 setCurrentItem方法 只在首次显示Fragment 生效而往后失效这么一个问题;举个复现例子,就是若我首次启动这个Fragment,滑动ViewPager 使 CurrentItem的位置为3;然后关掉 Fragment,再启动,那么该次启动的Fragment 的首个pager 位置会是上次的结束位置3,而不是我们期待的0,即使我在每次Fragment createView的时候都 setCurrentItem(0)了;

  研究了好一阵,造成这个问题的原因应该是Fragment的每次创建 用了 newInstance (为了保证不内存溢出);后来Google找到了该问题的解决办法: 

 Last thing, when you change your dataset you need to call the "notifyDataSetChanged" method that I mentioned above, and then you call the "setCurrentItem" method inside a handler. If you don't, your app will not work as expected.

ViewPager mPager = new ViewPager();
mPager.getAdapter().notifyDataSetChanged();  //This notify that you need to recreate the views

/*This is if you want to change the data and then go to a specific position
If you do not do this you will have a very Buggy Behavior*/
new Handler().post(new Runnable() {
@Override
public void run() {
    mPager.setCurrentItem(2); //Where "2" is the position you want to go
    }
});
  对, 因为数据会重新init ,所以办法 就是一定记得在调用 ViewPager 关联的 Adapter 的 notifyDataSetChanged()方法后,在 handler里面再调用 ViewPager 的 setCurrentItem方法,就OK啦. 我也是个android新人,所以为啥这样改的具体原因也还不是很明白就不乱说啦~

  看中文博客很少有关于这个问题的解答,所以写一篇;如需要更详细的解释 请转到这个链接研究啦:

   http://stackoverflow.com/questions/12008716/setcurrentitem-in-viewpager-not-scroll-immediately-in-the-correct-position




   

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值