问题描述
我有一个带有 ViewPager 的 Activity,它显示一堆图片.当它启动时,ViewPager 的位置是根据用户在前一个 Activity 中选择的内容设置的.类似于画廊.
I have an Activity with a ViewPager which displays a bunch of pictures. When it starts the ViewPager's position is set based on what the user selected in a previous Activity. Similar to a gallery.
我希望每次选择新页面时都调用 onPageSelected,即首次打开 Activity 或用户滑动到新页面时.
I want the onPageSelected to be called every time a new page is selected, i.e. when the Activity is first opened or when the user slides to a new page.
我这样设置起点:
mPager.setCurrentItem(index);
一切正常,除非调用 setCurrentItem 并将索引设置为 0,因为这不会触发 onPageSelected.
Everything works, except when setCurrentItem called with index set to 0 as this will not trigger onPageSelected.
mPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int index) {
Log.d(TAG, "onPageSelected " + index);
}
...
}
所以我的问题是;这是一个错误吗?如果是,我该怎么办?
So my question is; is this a bug, and if so what can I do about it?
推荐答案
到目前为止我找到的最干净的解决方案是引用您在 ViewPager 上设置的 onPageChangeListener(因为我认为没有ViewPager.getOnPageChangeListener() 方法),然后在设置好 ViewPager 的适配器后,调用:
The cleanest solution I've found to this so far is to take a reference to the onPageChangeListener you set on the ViewPager (since I don't think there's a ViewPager.getOnPageChangeListener() method), then after you've set the ViewPager's adapter, call:
onPageChangeListener.onPageSelected(viewPager.getCurrentItem());
但是,当前索引处的页面片段还没有被实例化(至少如果您使用的是 FragmentStatePagerAdapter),因此您可能需要将它包装在一个可运行的文件中,ala:
However, the fragment for the page at the current index won't have been instantiated yet (at least if you're using FragmentStatePagerAdapter), so you may need to wrap it in a runnable, ala:
viewPager.post(new Runnable(){
@Override
public void run() {
onPageChangeListener.onPageSelected(viewPager.getCurrentItem());
}
});
此外,如果在 onPageSelected 处理程序中需要对片段的引用,则必须自己进行.我为我的 FragmentStatePagerAdapter 使用了一个抽象基类,它覆盖了实例化和销毁方法,并从 SparseArray 添加/删除了片段.
Also, if within the onPageSelected handler you need a reference to the fragment, you'll have to do that yourself. I use an abstract base class for my FragmentStatePagerAdapter which overrides the instantiate and destroy methods, and adds/removes the fragments from a SparseArray.
这篇关于调用 setCurrentItem(0) 时不会触发 onPageSelected的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!