I am using android navigation components with bottom navigation view.
I have 3 fragments in my bottom navigation view, Fragments - A, B, and C.
Expected behavior:
To exit app on pressing back in any fragment.
Observed behavior: A -> B -> C -> A -> B-> back -> A -> back -> C -> back B -> back A -> back -> exit.
(Fragment stack is added for bottom navigation fragments) How to achieve my expected behavior?
My Problem is the same as this one in developer docs, but I have it in bottom navigation view:
https://developer.android.com/guide/navigation/navigation-getting-started#popupto_example_circular_logic
Code:
Bottom Navigation View Setup:
// Setup bottom navigation view
private fun setUpBottomNavigationView() {
// Nav host fragment
val host: NavHostFragment = supportFragmentManager
?.findFragmentById(R.id.main_activity_nav_host_fragment) as NavHostFragment
// Set up Action Bar
val navController = host.navController
// Setup bottom navigation view
mainActivityBinding.mainActivityBottomNavigationView.setupWithNavController(navController)
}
Navigation Graph:
<?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/activity_navigation"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="com.app.view.main.home.HomeFragment"
android:label="home_fragment"
tools:layout="@layout/home_fragment" />
<fragment
android:id="@+id/settingsFragment"
android:name="com.app.view.main.settings.SettingsFragment"
android:label="settings_fragment"
tools:layout="@layout/settings_fragment" />
<fragment
android:id="@+id/statisticsFragment"
android:name="com.app.view.main.statistics.StatisticsFragment"
android:label="statistics_fragment"
tools:layout="@layout/statistics_fragment" />
</navigation>
Bottom Navigation Menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@id/homeFragment"
android:icon="@drawable/ic_home_black_24dp"
android:title="@string/home"
app:showAsAction="ifRoom" />
<item
android:id="@+id/statisticsFragment"
android:icon="@drawable/ic_assessment_black_24dp"
android:title="@string/statistics"
app:showAsAction="ifRoom" />
<item
android:id="@id/settingsFragment"
android:icon="@drawable/ic_settings_black_24dp"
android:title="@string/settings"
app:showAsAction="ifRoom" />
</menu>
'in your main activity override onbackpress method and finish the Activity like this.'
'this will solve your problem'