I'm getting an IllegalArgumentException with the message "ID does not reference a View inside this Activity" when calling findNavController(requireActivity(), R.id.mainNavHostFragment) inside the onViewCreated() method of a Fragment. The Fragment is created by a FragmentStateAdapter for a ViewPager, and the issue only occurs when returning to the application after a configuration change.
The NavHostFragment is located in the Fragment's Activity, and the ID is correctly referenced in the call to findNavController(requireActivity(), R.id.mainNavHostFragment). The issue only occurs after a configuration change.
Nav host in activity_main.xml:
<fragment
android:id="@+id/mainNavHostFragment"
class="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
Fragments onViewCreated:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = try {
findNavController(view)
} catch (e: IllegalStateException) {
findNavController(requireActivity(), R.id.mainNavHostFragment)
}
keyboardManager.registerKeyboardConsumer(this)
}