我创建了一个导航类型为“tabs + swipe”的新活动。我在 getItem() 方法中进行了这些更改:
@Override
public Fragment getItem(int i) {
Fragment fragment ;
switch(i){
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 3:
fragment = new Fragment3();
break;
//
default : return null;
}
//set args if necessary
//return fragment
return fragment;
}
所以对于每个选项卡,我都定义了一个单独的类。一类是这样的:
public static class Fragment1 extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public Fragment1() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
View v = inflater.inflate(R.layout.center, null);
return v;
}
}
当我运行应用程序时,新活动成功启动,但是当我将屏幕滑动到第二个选项卡时,应用程序崩溃......这是 logcat:
02-16 08:48:43.328: E/AndroidRuntime(21541): FATAL EXCEPTION: main
02-16 08:48:43.328: E/AndroidRuntime(21541): java.lang.NullPointerException
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:394)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:389)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:99)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:801)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.support.v4.view.ViewPager.populate(ViewPager.java:992)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.support.v4.view.ViewPager.populate(ViewPager.java:881)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.support.v4.view.ViewPager$3.run(ViewPager.java:237)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.os.Handler.handleCallback(Handler.java:605)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.os.Handler.dispatchMessage(Handler.java:92)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.os.Looper.loop(Looper.java:137)
02-16 08:48:43.328: E/AndroidRuntime(21541): at android.app.ActivityThread.main(ActivityThread.java:4575)
02-16 08:48:43.328: E/AndroidRuntime(21541): at java.lang.reflect.Method.invokeNative(Native Method)
02-16 08:48:43.328: E/AndroidRuntime(21541): at java.lang.reflect.Method.invoke(Method.java:511)
02-16 08:48:43.328: E/AndroidRuntime(21541): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
02-16 08:48:43.328: E/AndroidRuntime(21541): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
02-16 08:48:43.328: E/AndroidRuntime(21541): at dalvik.system.NativeStart.main(Native Method)
请解决我的问题。