当来到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>
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
getActivity().finishAndRemoveTask();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this,callback);
}
你可以
做类似的事情
//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"
我找到了一种方法,但这不是一种方便的方法,但它对我有用。
使用 2.1.0-alpha02
nav_version_ktx = "2.1.0-alpha02"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version_ktx"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version_ktx"
和导航
var navHostFragment = supportFragmentManager.findFragmentById(R.id.my_nav_host_fragment)
bottom_home.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.navigation_home -> {
val backStackEntryCount = navHostFragment?.childFragmentManager?.fragments?.size
for (i in -1 until backStackEntryCount as Int) {
findNavController(R.id.my_nav_host_fragment).popBackStack()
}
findNavController(R.id.my_nav_host_fragment).popBackStack()
findNavController(R.id.my_nav_host_fragment).navigate(R.id.homeFragment)
}
return@OnNavigationItemSelectedListener true
}
R.id.navigation_notifications -> {
findNavController(R.id.my_nav_host_fragment).navigate(R.id.notificationFragment)
return@OnNavigationItemSelectedListener true
}
false
})