Search code examples
androidrotationfragmentscreendialogfragment

save value of a variable in a DialogFragment when the screen rotates


Well, I wanted to save value of a variable contained in a dialogFragment when the screen is rotated in Android. I've tried every method I could find on the internet, and none of them has worked for me. Some kill my application, and others simply were not doing anything.

I need a real and effective way to save the value of an EditText that is reset when the device screen rotates. The EditText is in a DialogFragment turn this into a FragmentActivity.

thank you very much


Solution

  • Set your fragment's retaingInstance flag to true:

    http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)

    This prevents Fragment instance from being recreated.

    Also be sure you don't recreate the fragment all the time:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    
        if (savedInstanceState == null) {
            Fragment f = new Myfragment();
            f.setRetainInstance(true);
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, f))
                .commit();
        }
    
    }
    

    Since View state is preserved during Activity recreation and your are keeping the same Fragment instance you don't need to save TextView value all the time.