我在活动中的ViewPager中添加了一个OnPageChangeListener。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mPageAdapter = new PageAdapter(fragmentManager);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mPageAdapter);
mPager.setOffscreenPageLimit(CACHE_SIZE);
mPager.addOnPageChangeListener(mOnPageChangeListener);
...
private ViewPager.SimpleOnPageChangeListener mOnPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int i) {
Log.d(TAG, "this: " + this);
ChartFragment chartFragment = mFragmentList.get(i).second; // crash when activity recreate............
...
我将所有片段存储在List中。
private List<Pair<String, ChartFragment>> mFragmentList = new ArrayList<Pair<String, ChartFragment>>();
private class PageAdapter extends FragmentPagerAdapter {
public Object instantiateItem(ViewGroup container, int position) {
mFragmentList.add(new Pair<String, ChartFragment>(...));
现在我使用DDMS停止我的应用程序进程并重新打开它,此页面在函数onPageSelected中崩溃。
我不知道为什么函数onPageSelected在ViewPager“init”之前执行。
我该如何解决这个问题?救命啊!
日志:
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
MyActivity$1.onPageSelected(MyActivity.java:101)
...
ViewPager.onRestoreInstanceState中的onPageSelected函数调用。
10-15 13:22:57.745 D/MyAccountActivity( 8998): at ...MyActivity$1.onPageSelected(MyActivity.java:103)
10-15 13:22:57.745 D/MyAccountActivity( 8998): at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1792)
10-15 13:22:57.745 D/MyAccountActivity( 8998): at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:547)
10-15 13:22:57.745 D/MyAccountActivity( 8998): at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:513)
10-15 13:22:57.745 D/MyAccountActivity( 8998): at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1319)
答案 0 :(得分:0)
在为ViewPager添加PageChangeListener之前,请确保“mFragmentList”中的数据可用。
在以下行
之前的“mFragmentList
”中获取数据
mPager.addOnPageChangeListener(mOnPageChangeListener);