从带有导航组件的后台文件中删除片段



我有一个PinCreateActivity,它有一个navHost片段,有两个片段PinSetup和PinCreate片段。

当"活动"启动时,PinSetup是默认片段,然后单击按钮导航到PinCreate片段。我想要的是从PinCreate片段,当用户点击后退按钮不转到PinSetup并像PinCreateActivity那样导航到backstack时。所以我想当我从PinSetup导航到PinCreate片段时,我必须从backstack中删除PinSetup。我该怎么做?

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" />
</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)
}

如果在弹出窗口时需要一些额外的逻辑,可以通过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>

最新更新