ナビゲーションの状態を保存、管理する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
以降のセクションでは、バックスタックを保存し、バックスタック内のエントリに関連付けられた状態を保存するための戦略について説明します。
バックスタックを保存する
優れたユーザー エクスペリエンスを実現するには、構成の変更やプロセスの終了など、さまざまなライフサイクル イベントでアプリのナビゲーション状態が保持されるようにすることが重要です。Navigation 3 では、バックスタックを所有するため、バックスタックの作成方法や保存方法に関する厳格なガイドラインはありません。ただし、Navigation 3 には、保存可能なバックスタック(rememberNavBackStack
)を提供する便利なメソッドが用意されています。
rememberNavBackStack
rememberNavBackStack
コンポーズ可能な関数は、構成の変更やプロセスの終了後も保持されるバックスタックを作成するように設計されています。
rememberNavBackStack
が正しく機能するには、バックスタック内の各キーが特定の要件を満たしている必要があります。
NavKey
インターフェースを実装する: バックスタック内のすべてのキーは NavKey
インターフェースを実装する必要があります。これは、キーを保存できることをライブラリに通知するマーカー インターフェースとして機能します。
@Serializable
アノテーションがある: NavKey
を実装するだけでなく、鍵クラスとオブジェクトに @Serializable
アノテーションを付ける必要があります。
次のスニペットは、rememberNavBackStack
の正しい実装を示しています。
@Serializable
data object Home : NavKey
@Composable
fun NavBackStack() {
val backStack = rememberNavBackStack(Home)
}
代替手段: ViewModel
に保存する
バックスタックを管理するもう 1 つの方法は、ViewModel
に保存することです。ViewModel
などのカスタム ストレージを使用してプロセスの終了後も永続化するには、次の操作を行う必要があります。
- キーがシリアル化可能であることを確認する:
rememberNavBackStack
と同様に、ナビゲーション キーはシリアル化可能である必要があります。
- シリアル化とシリアル化解除を手動で処理する: 各キーのシリアル化された表現を手動で永続ストレージ(
SharedPreferences
、データベース、ファイル)を保存します。
ViewModel
を NavEntry
にスコープ設定する
ViewModels
は、画面の回転などの構成変更後も UI 関連の状態を保持するために使用されます。デフォルトでは、ViewModels
は最も近い ViewModelStoreOwner
(通常は Activity
または Fragment
)にスコープされます。
ただし、ViewModel
のスコープを Activity
全体ではなく、バックスタック上の特定の NavEntry
(特定の画面またはデスティネーション)に設定することもできます。これにより、ViewModel
の状態は、その特定の NavEntry
がバックスタックの一部である間のみ保持され、NavEntry
がポップされるとクリアされます。
androidx.lifecycle:lifecycle-viewmodel-navigation3
アドオン ライブラリには、これを容易にする NavEntryDecorator
が用意されています。このデコレータは、NavEntry
ごとに ViewModelStoreOwner
を提供します。NavEntry
のコンテンツ内に ViewModel
を作成すると(Compose で viewModel()
を使用するなど)、バックスタック上の特定の NavEntry
のキーに自動的にスコープが設定されます。つまり、NavEntry
がバックスタックに追加されると ViewModel
が作成され、削除されると消去されます。
NavEntryDecorator
を使用して ViewModel
を NavEntry
にスコープ設定する手順は次のとおりです。
androidx.lifecycle:lifecycle-viewmodel-navigation3
依存関係を app/build.gradle.kts
ファイルに追加します。
NavDisplay
を作成するときに、entryDecorators
のリストに rememberSavedStateNavEntryDecorator()
を追加します。
NavDisplay
に他のデコレーターを追加します。
NavDisplay(
entryDecorators = listOf(
// Add the default decorators for managing scenes and saving state
rememberSceneSetupNavEntryDecorator(),
rememberSavedStateNavEntryDecorator(),
// Then add the view model store decorator
rememberViewModelStoreNavEntryDecorator()
),
backStack = backStack,
entryProvider = entryProvider { },
)
このページのコンテンツやコードサンプルは、コンテンツ ライセンスに記載のライセンスに従います。Java および OpenJDK は Oracle および関連会社の商標または登録商標です。
最終更新日 2025-07-27 UTC。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["必要な情報がない","missingTheInformationINeed","thumb-down"],["複雑すぎる / 手順が多すぎる","tooComplicatedTooManySteps","thumb-down"],["最新ではない","outOfDate","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["サンプル / コードに問題がある","samplesCodeIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-07-27 UTC。"],[],[],null,["# Save and manage navigation state\n\nThe following sections describe strategies for saving your back stack and\nstoring state associated with entries on your back stack.\n\nSave your back stack\n--------------------\n\nEnsuring your app's navigation state persists across various lifecycle events,\nincluding configuration changes and process death, is crucial for a good user\nexperience. In Navigation 3, you own your back stack, so there aren't strict\nguidelines on how you should create or save it. However, Navigation 3 does offer\na convenience method that provides you with a saveable back stack:\n[`rememberNavBackStack`](/reference/kotlin/androidx/navigation3/runtime/package-summary#rememberNavBackStack(kotlin.Array)).\n\n### Use `rememberNavBackStack`\n\nThe `rememberNavBackStack` composable function is designed to create a back\nstack that persists across configuration changes and process death.\n\nFor `rememberNavBackStack` to function correctly, each key in your back stack\nmust adhere to specific requirements:\n\n- **Implement `NavKey` interface** : Every key in the back stack must implement the [`NavKey`](/reference/kotlin/androidx/navigation3/runtime/NavKey) interface. This acts as a marker interface that signals to the library that the key can be saved.\n- **Have the `@Serializable` annotation** : In addition to implementing `NavKey`, your key classes and objects must be marked with the `@Serializable` annotation.\n\nThe following snippet shows a correct implementation of `rememberNavBackStack`:\n\n\n```kotlin\n@Serializable\ndata object Home : NavKey\n\n@Composable\nfun NavBackStack() {\n val backStack = rememberNavBackStack(Home)\n}https://github.com/android/snippets/blob/26d364466ee1c03d658ba2f0905f7cc1a97afefa/compose/snippets/src/main/java/com/example/compose/snippets/navigation3/savingstate/SavingStateSnippets.kt#L30-L36\n```\n\n\u003cbr /\u003e\n\n### Alternative: Storing in a `ViewModel`\n\nAnother approach to managing your back stack is to store it in a `ViewModel`.\nFor persistence through process death when using a `ViewModel` or any other\ncustom storage, you need to:\n\n- **Ensure your keys are serializable** : Just like with `rememberNavBackStack`, your navigation keys must be serializable.\n- **Handle serialization and deserialization manually** : You're responsible for manually saving the serialized representation of each key to, and deserializing it from, persistent storage (e.g., `SharedPreferences`, a database, or a file) when your app is going into the background or being restored.\n\nScoping `ViewModel`s to `NavEntry`s\n-----------------------------------\n\n`ViewModels` are used to retain UI-related state across configuration changes,\nsuch as screen rotations. By default, `ViewModels` are scoped to the nearest\n`ViewModelStoreOwner`, which is typically your `Activity` or `Fragment`.\n\nHowever, you might want to scope a `ViewModel` to a specific `NavEntry` (i.e., a\nspecific screen or destination) on the back stack, rather than the entire\n`Activity`. This ensures that the `ViewModel`'s state is retained only while\nthat particular `NavEntry` is part of the back stack, and is cleared when the\n`NavEntry` is popped.\n\nThe `androidx.lifecycle:lifecycle-viewmodel-navigation3` add-on library provides\na `NavEntryDecorator` that facilitates this. This decorator provides a\n`ViewModelStoreOwner` for each `NavEntry`. When you create a `ViewModel` inside a\n`NavEntry`'s content (e.g., using `viewModel()` in Compose), it is automatically\nscoped to that specific `NavEntry`'s key on the back stack. This means the\n`ViewModel` is created when the `NavEntry` is added to the back stack, and\ncleared when it's removed.\n\nTo use `NavEntryDecorator` for scoping `ViewModel`s to `NavEntry`s, follow these\nsteps:\n\n1. Add the `androidx.lifecycle:lifecycle-viewmodel-navigation3` dependency to your `app/build.gradle.kts` file.\n2. Add [`rememberSavedStateNavEntryDecorator()`](/reference/kotlin/androidx/navigation3/runtime/package-summary#rememberSavedStateNavEntryDecorator(androidx.compose.runtime.saveable.SaveableStateHolder)) to the list of `entryDecorators` when constructing a `NavDisplay`.\n3. Add other decorators into your `NavDisplay`.\n\n\n```kotlin\nNavDisplay(\n entryDecorators = listOf(\n // Add the default decorators for managing scenes and saving state\n rememberSceneSetupNavEntryDecorator(),\n rememberSavedStateNavEntryDecorator(),\n // Then add the view model store decorator\n rememberViewModelStoreNavEntryDecorator()\n ),\n backStack = backStack,\n entryProvider = entryProvider { },\n)https://github.com/android/snippets/blob/26d364466ee1c03d658ba2f0905f7cc1a97afefa/compose/snippets/src/main/java/com/example/compose/snippets/navigation3/savingstate/SavingStateSnippets.kt#L45-L55\n```\n\n\u003cbr /\u003e"]]