Fragment of destruction and getActivity () null pointer exception

Fragment can not use the same Activity to finish () destroy ourselves, but we know that when Fragment click the back key is to destroy the current fragment, so:

 getActivity().onBackPressed();//销毁自己

Which, getActivity () throws null pointer exception may be the reason is because the memory restart, Fragment likely to call getActivity () before it is attached to the Activity. The solution is to rewrite onAttach Fragment () method, as follows

private Activity activity;
public void onAttach(Context context) {
      super.onAttach(context);
      this.activity = (Activity) context;
}

Instead of using a global variable activity getActivity (). which is

activity.onBackPressed();//销毁自己

 

Guess you like

Origin blog.csdn.net/Smile_Qian/article/details/81914437