Activity content disappears when rotating [closed]

巧了我就是萌 提交于 2019-12-25 18:37:43

问题


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();
        }
    }
}

回答1:


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;
}



回答2:


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(...);


来源:https://stackoverflow.com/questions/41231235/activity-content-disappears-when-rotating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!