Fixed
Status Update
Comments
fl...@gmail.com <fl...@gmail.com> #2
It is not possible for the view of the NavHostFragment to be available in the onCreate() of the Activity. In this case, the NavHostFragment lifecycle method follows the Activity lifecycle methods directly therefore, when the activity is on onCreate() so is the NavHostFragment. However, if the Fragment Lifecycle was driven with a LifecycleObserver (https://issuetracker.google.com/issues/127528777 ), onCreate() could be dispatched for a Fragment separately from the onCreate() for an Activity (or a parent Fragment if using a child Fragment). This means that if you were using a LifecycleObserver, it would be possible for the views to be available when onCreate() is dispatched and findNavController() would work in the LifecycleObserver's onCreate().
This is being tracked byhttps://issuetracker.google.com/issues/143145612 .
This is being tracked by
fl...@gmail.com <fl...@gmail.com> #3
Possible workaround #4: call findNavController in onPostCreate.
il...@google.com <il...@google.com>
il...@google.com <il...@google.com>
il...@google.com <il...@google.com> #5
#4: Why can't Navigation.findNavController(activity, id) do that?
public static NavController findNavController(@NonNull Activity activity, @IdRes int viewId) {
if (activity instanceof FragmentActivity) {
NavHostFragment navHostFragment = (NavHostFragment)(((FragmentActivity)activity).getSupportFragmentManager().findFragmentById(viewId));
return navHostFragment.getNavController();
}
View view = ActivityCompat.requireViewById(activity, viewId);
NavController navController = findViewNavController(view);
if (navController == null) {
throw new IllegalStateException("Activity " + activity + " does not have a NavController set on " + viewId);
}
return navController;
}
public static NavController findNavController(@NonNull Activity activity, @IdRes int viewId) {
if (activity instanceof FragmentActivity) {
NavHostFragment navHostFragment = (NavHostFragment)(((FragmentActivity)activity).getSupportFragmentManager().findFragmentById(viewId));
return navHostFragment.getNavController();
}
View view = ActivityCompat.requireViewById(activity, viewId);
NavController navController = findViewNavController(view);
if (navController == null) {
throw new IllegalStateException("Activity " + activity + " does not have a NavController set on " + viewId);
}
return navController;
}
Description
this is the first time I file a bug, so I don't really know how to do that properly.
I noticed that if I create a fragment instance in an activity, add it to the container, remove it with the FragmentTransaction's remove method (which destroys the fragment instance) and then later use the same fragment variable in the activity to add it back to the container (which calls onCreate again), no LifecycleObserver can be added in the fragment's onCreate method, because the fragment is still in DESTROYED state.