今天遇到了一个项目上的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