onSaveInstanceState called after fragment replaced

Problem

onSaveInstanceState is being called on device rotation for a fragment which has been replaced in a fragment transaction. This is causing an IllegalStateException with the message "Content view not yet created.

Research

I have found the following two answers which seem most relevant

Using onSaveInstanceState with fragments in backstack?

onSaveInstanceState of previous fragment is called on-orientation of current fragment

What I've tried already

Following the answer to the second question I have removed addtobackstack from the fragment transaction but am still getting the error.

I read the accepted answer to the first question but am not sure how to get a fragment reference within onSaveInstanceState for the activity. I also don't particularly want to save that fragment, when the user leaves that fragment it's state does not need to be saved.

I have also tried adding if (getView() != null) {...} to the onSaveInstanceState in the fragment but this made no difference.

Questions

  • Why is onSaveInstanceState being called even though the fragment hasn't been added to the back stack?
  • Is the right approach to somehow kill the fragment when the user is done with it?
  • Is there a different solution?
  • Thank you in advance for your help.

    Andrew

    Edit

    If I remove addtobackstack(null) from the transaction which adds the fragment and the one where it is removed the problem goes away, but then so does an important piece of functionality... I could add that case to my onBackPressed override function but it seems a bit of a hack, and not in a good way.


    Adding an isVisible() check onSaveInstanceState of the fragment in the backstack should work.

    No need to retain instance state when it is not visible.

    链接地址: http://www.djcxy.com/p/58704.html

    上一篇: 在后台堆栈上的所有片段,在旋转后在onSaveInstanceState中都有空值

    下一篇: 片段替换后调用onSaveInstanceState