You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Navigation Component时已切换Fragment的onSaveInstanceState仍被调用的问题

Why onSaveInstanceState() Runs for a "Switched Away" Fragment in Navigation Component

Great question! Let’s break down exactly why this is happening, and how it ties into how Navigation Component manages fragments:

  • Navigation Component keeps old fragments in the back stack
    When you navigate from one fragment to another using Navigation Component, it automatically adds the previous fragment to the back stack (just like if you called addToBackStack() manually with the old FragmentManager). This means the old fragment isn’t destroyed—it’s just moved to the STOPPED state, sitting in memory waiting in case the user presses the back button to return to it.

  • Screen rotation triggers full activity state preservation
    Rotating the screen causes a configuration change, which makes the system destroy and recreate your entire activity. During this process, the system saves the state of all active fragment instances—including those that are stopped and sitting in the back stack. The onSaveInstanceState() method is part of this preservation process, so the old fragment gets called because the system wants to retain its state for when (or if) it’s brought back to the foreground.

  • The "expected" behavior vs. Navigation Component’s design
    It’s easy to assume switching fragments would destroy the old one, but Navigation Component’s core design is to handle navigation flows via the back stack. This ensures consistent back button behavior across your app. The old fragment only gets fully destroyed when you explicitly remove it from the back stack.

How to Fix It (If You Want to Destroy the Old Fragment)

If you don’t need the old fragment to stick around (and thus don’t want its onSaveInstanceState() to run), configure your navigation action to clear it from the back stack using popUpTo and popUpToInclusive=true:

<action
    android:id="@+id/action_FragmentA_to_FragmentB"
    app:destination="@id/FragmentB"
    app:popUpTo="@id/FragmentA"
    app:popUpToInclusive="true"/>

This tells Navigation Component to remove FragmentA from the back stack when navigating to FragmentB. Now, when you rotate the screen, FragmentA is no longer in memory, so its onSaveInstanceState() won’t execute.

内容的提问来源于stack exchange,提问作者Marti Serra Molina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 17:32:55