Search code examples
androidandroid-dialogfragment

DialogFragment / orientation switch


I have a fairly simple DialogFragment. It looks something like:

import android.support.v4.app.DialogFragment;

public class MyDialogFragment extends DialogFragment {

    private String mData = "empty";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(LOG_TAG, "onCreate");

        setStyle(DialogFragment.STYLE_NO_TITLE, 0);
        // setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.mydialog, container);

        ....

        return view;
    }

    public setData(String _data) {
        mData = _data;
    }
}

I load this fragment like so from my FragmentActivity:

FragmentManager lFM = getSupportFragmentManager();
MyDialogFragment lDialog = new MyDialogFragment();
lDialog.setData("not empty");
lDialog.show(lFM, "MyDialog");

The code as above works fine. However I would like to retain the fragment on an orientation switch so that the mData field is preserved. If I add setRetainInstance(true); (and after sticking in some debug) I can see that the fragment is indeed retained on an orientation switch - onCreate() is not being called this time. I can see onCreateView() is being called and I return a correct View object, but the dialog is not shown on the screen. What am I missing?


Solution

  • Try the following logic in your fragment activity:

    Use the put methods to store values in onSaveInstanceState():

    protected void onSaveInstanceState(Bundle icicle) {
      super.onSaveInstanceState(icicle);
      icicle.putBoolean("dialogDisplayed", value);    // set value = true when displayin dialog...
    }
    

    And restore the values in onCreate():

     public void onCreate(Bundle icicle) {
       if (icicle != null){
         value = icicle.getBoolean("dialogDisplayed");
       }
       if(value)
           //Display Dialog here.... 
    
     }