到HomeFragment(startDestination)时如何清除所有堆栈,我想在用户通过导航组件按回homeFragment时关闭应用程序。

 <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"
                app:startDestination="@+id/homeFragment">


        <fragment android:id="@+id/homeFragment"
                  android:name="ui.fragment.home.HomeFragment"
                  tools:layout="@layout/fragmet_home"
                  android:label="HomeFragment"
                  app:launchSingleTop="true"
                  app:popUpToInclusive="true">

            <action android:id="@+id/action_homeFragment_to_notificationFragment"
                    app:destination="@id/notificationFragment"
                    app:popUpTo="@+id/homeFragment"
                    app:enterAnim="@anim/pop_enter"
                    app:exitAnim="@anim/pop_exit"
                    app:popEnterAnim="@anim/right_in"
                    app:popExitAnim="@anim/right_out"/>
       </Fragment>

       <fragment  android:id="@+id/notificationFragment"
                  android:name="ui.fragment.notification.NotificationFragment"
                  tools:layout="@layout/fragment_notification"/>
 </navigation>

最佳答案

你可以做类似的事情

//backpress only for this fragment
requireActivity().onBackPressedDispatcher.addCallback(this@HomeFragment) {
    // handle back event
    activity?.finishAndRemoveTask()
}

我正在使用
nav_version_ktx = "2.1.0-alpha06"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version_ktx"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version_ktx"

关于android - 来自Homefragment的Android导航组件关闭应用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57087178/

10-10 09:26