我在Activity中的ViewPager中添加了一個OnPageChangeListener。ViewPager.OnPageChangeListener在ViewPager完成之前運行初始化
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............
...
而我將所有片段存儲在列表中。
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 exec在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)
安置自己的logcat之前在 「
mFragmentList
」獲取數據負載。 –
@ mr.icetea日誌說「mFragmentList大小爲0」,因爲instantiateItem還沒有運行。 –
如果你的崩潰是因爲indexoutofBounds,然後檢查像「mFragmentList.get(i).second」。 –