假设在到达目的地 C 之后,返回堆栈包含每个目的地(A、B、C)的一个实例。您需要确保在操作中或调用 navigate() 时定义了 popUpTo() 和 inclusive,这会将用户从目的地 C 引导至目的地 A。
在这种情况下,当用户从目的地 C 导航回目的地 A 时,NavController 也弹出到 A。这意味着,它会从堆栈中移除 B 和 C。使用 inclusive = true 时,它还会弹出第一个 A,从而有效地清除堆栈。
Compose 实现
以下是在 Compose 中循环 popUpTo() 的解决方案的实现:
// When creating your `NavGraph` in your `NavHost`.composable("c"){DestinationC(onNavigateToA={navController.navigate("a"){popUpTo("a"){inclusive=true}}},)}
[null,null,["最后更新时间 (UTC):2025-07-27。"],[],[],null,["# Circular navigation\n\nA clear example of where you need to pop back to a destination is when your\nnavigation is circular. This document outlines that use case.\n\nScenario\n--------\n\nImagine your app has three destinations: A, B, and C. It also has actions that\nlead from A to B, B to C, and C back to A. The corresponding navigation graph\nappears as follows:\n**Figure 1.** A circular navigation graph with three destinations: A, B, and C.\n\nWith each navigation action, the `NavController` adds the new destination to the\nback stack. As such, repeatedly navigating through the flow in the diagram would\ncause your back stack would to contain multiple sets of each destination: A, B,\nC, A, B, C, A, B, C.\n\nSolution\n--------\n\nTo avoid repetition in your back stack, specify [`popUpTo()`](/guide/navigation/backstack#pop) and\n[`inclusive`](/guide/navigation/backstack#pop-back-destination) in your call to `NavController.navigate()` or in your\nnavigation action.\n\nConsider a case where after reaching destination C, the back stack contains one\ninstance of each destination: A, B, C. You need to ensure that you have defined\n`popUpTo()` and `inclusive` in the action or call to `navigate()` that takes the\nuser from destination C to destination A.\n\nIn this case, when the user navigates from destination C back to destination A,\nthe `NavController` also pops up to A. This means that it removes B and C from\nthe stack. With `inclusive = true`, it also pops the first A, effectively\nclearing the stack.\n| **Note:** This is similar to calling [`popBackStack()` and passing `inclusive`](/guide/navigation/backstack#pop-back-destination).\n\n### Compose implementation\n\nThe following is the implementation of the solution for circular `popUpTo()` in\nCompose: \n\n // When creating your `NavGraph` in your `NavHost`.\n composable(\"c\") {\n DestinationC(\n onNavigateToA = {\n navController.navigate(\"a\") {\n popUpTo(\"a\") {\n inclusive = true\n }\n }\n },\n )\n }\n\n### Views implementation\n\nThe following is the implementation of the solution for circular `popUpTo` in\nViews: \n\n \u003cfragment\n android:id=\"@+id/c\"\n android:name=\"com.example.myapplication.C\"\n android:label=\"fragment_c\"\n tools:layout=\"@layout/fragment_c\"\u003e\n\n \\\u003caction\n android:id=\"@+id/action_c_to_a\"\n app:destination=\"@id/a\"\n app:popUpTo=\"@+id/a\"\n app:popUpToInclusive=\"true\"/\\\u003e\n \u003c/fragment\u003e"]]