如何触发后退按钮在多个Fragment Android后返回主屏幕



我正在构建一个应用程序,它有这样的导航:

Login Fragment (Start Destination) ->初始设置Fragment ->家片段。

在Login Fragment中,有一个检查用户是否已经使用SharedPreference登录。如果是,用户将被重定向到初始设置。

在初始设置片段中,有一个检查用户是否设置了帐户。如果是,用户将被重定向到Home Fragment。

我想问的是,例如,我正在登录到应用程序,我将被重定向到初始设置片段。因为我已经设置了账号,应用程序会把我重定向到Home Fragment。那么,我如何触发后退按钮去主屏幕,而不是以前的片段(初始片段)?

到目前为止我所理解的是,我需要从backstack中删除那些初始片段和登录片段。我尝试在我的导航。xml上设置弹出行为,但仍然不起作用。

这是navigation.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/navigation"
app:startDestination="@id/loginFragment">
<fragment
android:id="@+id/loginFragment"
android:name="com.main.netwallet.login.LoginFragment"
android:label="fragment_login"
tools:layout="@layout/fragment_login" >
<action
android:id="@+id/action_loginFragment_to_registerFragment"
app:destination="@id/registerFragment" />
<action
android:id="@+id/action_loginFragment_to_initialSettingFragment"
app:destination="@id/initialSettingFragment" />
<action
android:id="@+id/action_loginFragment_to_homeFragment"
app:destination="@id/homeFragment" />
</fragment>
<fragment
android:id="@+id/registerFragment"
android:name="com.main.netwallet.register.RegisterFragment"
android:label="fragment_register"
tools:layout="@layout/fragment_register" >
<action
android:id="@+id/action_registerFragment_to_initialSettingFragment"
app:destination="@id/initialSettingFragment" />
</fragment>
<fragment
android:id="@+id/homeFragment"
android:name="com.main.netwallet.home.HomeFragment"
android:label="fragment_home"
tools:layout="@layout/fragment_home" >
<action
android:id="@+id/action_homeFragment_to_loginFragment"
app:destination="@id/loginFragment"
app:popUpTo="@id/initialSettingFragment"
app:popUpToInclusive="false" />
</fragment>
<fragment
android:id="@+id/initialSettingFragment"
android:name="com.main.netwallet.initialSetting.InitialSettingFragment"
android:label="InitialSettingFragment"
tools:layout="@layout/fragment_initial_setting">
<action
android:id="@+id/action_initialSettingFragment_to_homeFragment"
app:destination="@id/homeFragment"
app:popUpTo="@id/loginFragment"
app:popUpToInclusive="true" />
</fragment>
</navigation>

那么我需要改变什么呢?

提前谢谢你

p。我还使用了findNavController.navigate(fragmentdirections . androiddaction)而不是(R.id.fragmentId)

由于您使用的是Jatpack导航,因此这里将通过示例和练习来解释所有内容。

也给你一个小总结,你需要清除你的背堆栈,当你从一个片段导航到另一个片段。换句话说就是"不要跟踪历史"。

最新更新