我在ViewPager中有3個頁面:Tab0,Tab1,Tab2的實例。在主Activity中,我將Sectionse變量中每個選項卡的實例存儲在SectionsPagerAdapter的getItem()函數中。NullPointerException與ViewPager在應用程序被殺後
我認爲ViewPager總是初始化當前標籤頁,左邊的標籤頁和右邊的標籤頁。
這是我的情況:Tab0 t0; Tab1 t1; Tab2 t2;
的應用程序工作正常開始。但是,如果我按主頁按鈕(觸發onPause()
),殺死應用程序從任務殺手(或假設Android本身已殺死它),並再次打開應用程序,我得到NullPointerExceptions在onPageSelected
,因爲t0, t1 and t2
現在爲空。
這是我的onCreate方法:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int pos) {
switch(pos){
case 1:
t1.lookup()
break;
case 0:
t0.doSomething();
break;
case 2:
t2.someThingElse();
break;
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
mViewPager.setCurrentItem(1,true);
}
這是我的FragmentPagerAdapter(這是我的活動內的嵌套類):
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment;
switch(position){
case 0:
fragment = t0 = new Tab0();
break;
case 1:
fragment = t1 = new Tab1();
break;
case 2:
fragment = t2 = new Tab2();
break;
default:
fragment=null;
}
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position + 1);
if(fragment!=null)
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 1:
return getString(R.string.T1).toUpperCase(l);
case 0:
return getString(R.string.T0).toUpperCase(l);
case 2:
return getString(R.string.T2).toUpperCase(l);
}
return null;
}
}