Search code examples
androidandroid-fragmentsandroid-orientationandroid-dialogfragment

android fragment orientation change


EDIT:

I have a DialogFragment where the reference inside the parent Activity is NULL after I change device orientation. How do I fix this?

Fragment creation:

MyFragment myFragment = MyFragment.newInstance(title);
myFragment.show(getFragmentManager(), tag);

After orientation change:

MyFragment myFragment = (MyFragment)getFragmentManager().findFragmentByTag(tag);
myFragment.dismiss();  //NULL pointer exception here

Solution

  • myFragment.setRetainInstance(true); for the rescue.


    Edit:

    Also Override onDestroyView in your DialogFragment:

    @Override
    public void onDestroyView() {
      if (getDialog() != null && getRetainInstance())
        getDialog().setOnDismissListener(null);
      super.onDestroyView();
    }
    

    This is a result of the following issue: http://code.google.com/p/android/issues/detail?id=17423