在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=".MyApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
(2)创建Application,以单利的形式提供对外引用
public class MyApplication extends Application {
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static MyApplication getInstance(){
// 这里不用判断instance是否为空
return instance;
}
}
(3)在程序中使用
Context context = MyApplication.getInstance();
Toast.makeText(context, "Your Toast Message", Toast.SHORT_TOAST).show();