android fragment onRestoreInstanceState

十年热恋 提交于 2019-11-26 10:28:44

问题


Am I missing something or do Fragments not have a onRestoreInstanceState() method? If not, how do I go about attaining something similar?


回答1:


Fragments do not have an onRestoreInstanceState method.

You can achieve the same result in onActivityCreated, which receives a bundle with the saved instance state (or null).

Check the source code here.




回答2:


I know, that you have accepted answer, but you should read the official documentation about fragments, and it says (paragraph "Handling the Fragment Lifecycle"):

You can retain the state of a fragment using a Bundle, in case the activity's process is killed and you need to restore the fragment state when the activity is recreated. You can save the state during the fragment's onSaveInstanceState() callback and restore it during either onCreate(), onCreateView(), or onActivityCreated()

So, you can use that suits you best: onCreate(), onCreateView(), or onActivityCreated()




回答3:


In Fragments guide's ListFragment example you can find:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("curChoice", mCurCheckPosition);
}

Which you can use like this:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        // Restore last state for checked position.
        mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
    }
}

onActivityCreated() is invoked after the fragment returns back from the stack.




回答4:


onViewStateRestored of Fragment is the equivalent of onRestoreInstanceState of Activity. But it is called after onActivityCreated(Bundle) and before onStart().



来源:https://stackoverflow.com/questions/5412746/android-fragment-onrestoreinstancestate

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