在android开卡中Activity+ViewPager+Fragment几乎是每一个项目中都会使用到的结构,在Fragment中如果需要使用到Context对象一般就是getActivity()。但是如果Activity被销毁的话,getActivity()便会返回null。
解决方案有以下几种:
1.不保存fragment的状态:在Activity中重写onSaveInstanceState方法,将super.onSaveInstanceState(outState);注释掉,让其不再保存Fragment的状态,达到fragment随MyActivity一起销毁的目的。
2.重建时清除已经保存的fragment的状态:在恢复Fragment之前把Bundle里面的fragment状态数据给清除。方法如下:
if(savedInstanceState!= null)
{
String FRAGMENTS_TAG = "Android:support:fragments";
savedInstanceState.remove(FRAGMENTS_TAG);
}
3.使用全局Application得到的Context
(1)在Manifest中注册Application
<application
android:name=