Skip to content Skip to sidebar Skip to footer

Activity Content Disappears When Rotating

Have fragment on activity, and when rotation content disappears. Any idea what is wrong? public class MenuActivity extends AppCompatActivity { static MenuActivity menuActivity

Solution 1:

You must save the instance state of your fragment. You must save the state of your fragment from your activity AND from your fragment. Basically, the activity triggers the fragment to save its instance state. From the activity, you can do something like this:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //Save the fragment's instancegetSupportFragmentManager().putFragment(outState, "messageFragment", mFragment );

}

Then you restore it in onCreate like this:

if( savedInstanceState != null )
    mFragment = (MessageListFrgment) getSupportFragmentManager().getFragment( savedInstanceState, "messageFragment" );

If the only things you need to save are the content of TextViews, this should be enough. If you have variables to save for example, then you need to do something similar in the fragment. The principle for the fragment is basically the same.

@OverridepublicvoidonSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // Save your variables in the bundle
    outState.put...;
}

The difference with the fragment is that the restoring is done both in onCreate and onCreateView depending on what you saved and what you want to do with the saved content.

if( savedInstanceState != null )
    mObject = savedInstanceState.get(...);

Solution 2:

inside Fragment call this method:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);
}

Also you need to check whether View is null or not, and prevent from recreating it.

@Nullable@OverridepublicViewonCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (view == null) {
        view = inflater.inflate(R.layout.fragment, container, false);
        // ...
    }
    return view;
}

Post a Comment for "Activity Content Disappears When Rotating"