Within an Android app that I wrote, the navigation stops working correctly after the app executes the following two lines of Kotlin code:
val navControl = activity?.findNavController(R.id.fragNavHost)
navControl.navigate(R.id.actChaptersToRead)
I reproduced the same behavior by starting with the standard project "Bottom Navigation Views Activity" that Android Studio creates from the File -> New Project menu item.
To reproduce the behavior, I did the following:
- Created a new "Bottom Navigation Views Activity".
- Added a button to the fragment_dashboard.xml layout. This is the 2nd of three layouts that the navigation controller navigates.
<Button
android:id="@+id/button_to_notifications"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="To Notifications"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_dashboard" />
- Made the button navigate to the third fragment (fragment_notifications.xml) by adding this Kotlin code to onCreateView in DashboardFragment.kt
val button: Button = binding.buttonToNotifications
button.setOnClickListener { view: View ->
val navController = view.findNavController()
navController.navigate(R.id.navigation_notifications)
}
After running the app, I pressed the "Dashboard" icon in the bottom navigation view which caused the app to navigate to the fragment_dashboard. (See screenshot below.) Then I pressed the "To Notifications" button that I added in step 2 above which caused the app execute the onClickListener in step 3 above and to navigate to the fragment_notifications. However, at this point, when I press the "Dashboard" icon in the bottom navigation view, the app will not navigate to the fragment_dashboard. Instead, it stays on the fragment_notifications.
There are no errors in Logcat. There are two warnings that my be related.
- OnBackInvokedCallback is not enabled for the application. Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
- Compiler allocated 4533KB to compile void android.view.ViewRootImpl.performTraversals()
What am I doing wrong in the Kotlin code in step 3 that causes the navigation to break after that code is executed?
