Activity content disappears when rotating [closed]

2019-09-21 15:15发布

Have fragment on activity, and when rotation content disappears. Any idea what is wrong?

public class MenuActivity extends AppCompatActivity {

    static MenuActivity menuActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        menuActivity = this;

        setContentView(R.layout.menu);

        App.setContext(this);

        if (savedInstanceState == null) {

            getFragmentManager().beginTransaction().add(R.id.frameLayout, new MessageListFragment()).commit();
        }
    }
}

2条回答
手持菜刀,她持情操
2楼-- · 2019-09-21 15:39

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 instance
    getSupportFragmentManager().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.

@Override
public void onSaveInstanceState(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(...);
查看更多
劳资没心,怎么记你
3楼-- · 2019-09-21 15:45

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
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (view == null) {
        view = inflater.inflate(R.layout.fragment, container, false);
        // ...
    }
    return view;
}
查看更多
登录 后发表回答