我有一個帶有 navHost 片段的 PinCreateActivity,其中包含 2 個片段 PinSetup 和 PinCreate 片段。
當 Activity 啟動時,PinSetup 是默認片段,然后單擊按鈕我導航到 PinCreate 片段。我想要的是來自 PinCreate 片段,當用戶單擊后退按鈕而不是像 PinCreateActivity 那樣轉到 PinSetup 并導航到后臺堆疊時。所以我想當我從 PinSetup 導航到 PinCreate 片段時,我必須從 backStack 中洗掉 PinSetup。我怎樣才能做到這一點?
導航圖.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@ id/pin_create_nav_graph"
app:startDestination="@id/pinSetupFragment">
<fragment
android:id="@ id/pinSetupFragment"
android:name="com.example.ui.fragments.pin.PinSetupFragment"
android:label="Create PIN"
tools:layout="@layout/fragment_pin_setup" >
<action
android:id="@ id/action_pinSetupFragment_to_pinCreateFragment"
app:destination="@id/pinCreateFragment" />
</fragment>
<fragment
android:id="@ id/pinCreateFragment"
android:name="com.example.ui.fragments.pin.PinCreateFragment"
android:label="Your PIN"
tools:layout="@layout/fragment_pin_create" />
</navigation>
PinCreateActivity
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
...
navController = Navigation.findNavController(this, R.id.pin_create_host_fragment)
// onClick
navController.navigate(R.id.action_pinSetupFragment_to_pinCreateFragment)
}
uj5u.com熱心網友回復:
如果您在彈出視窗時需要一些額外的邏輯,您可以通過 Kotlin 代碼以編程方式執行此操作。但是,如果您只需PinSetupFragment要從后臺堆疊中洗掉,則可以在導航圖 xml 檔案中執行此操作。
因此,如果您只是要彈出片段而沒有任何其他額外的邏輯,PinSetupFragment那么從后臺堆疊彈出的最佳方法是更新您的navigation_graph.xml檔案。
只需將這兩行添加到您的操作中:
app:popUpTo="@id/pinSetupFragment"
app:popUpToInclusive="true"
結果,您的navigation_graph.xml檔案將如下所示:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@ id/pin_create_nav_graph"
app:startDestination="@id/pinSetupFragment">
<fragment
android:id="@ id/pinSetupFragment"
android:name="com.example.ui.fragments.pin.PinSetupFragment"
android:label="Create PIN"
tools:layout="@layout/fragment_pin_setup" >
<action
android:id="@ id/action_pinSetupFragment_to_pinCreateFragment"
app:destination="@id/pinCreateFragment"
app:popUpTo="@id/pinSetupFragment"
app:popUpToInclusive="true" />
</fragment>
<fragment
android:id="@ id/pinCreateFragment"
android:name="com.example.ui.fragments.pin.PinCreateFragment"
android:label="Your PIN"
tools:layout="@layout/fragment_pin_create" />
</navigation>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453729.html
標籤:科特林 安卓片段 安卓架构导航 android-jetpack-导航 安卓导航图
