Fixed
Status Update
Comments
il...@google.com <il...@google.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
la...@gmail.com <la...@gmail.com> #3
Possible workaround #4: call findNavController in onPostCreate.
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
Version used: 1.2.2
The UseRequireInsteadOfGet lint checks in androidx-fragment 1.2.2 can detect false positives. Consider the following Java code in a Fragment:
View view = getSomeCompletelyUnrelatedView();
Objects.requireNonNull(view);
results in the following lint error:
Error: Use requireView() instead of Objects.requireNonNull(view) [UseRequireInsteadOfGet]
which would be valid if view was the result of a getView() call but it isn't.
Workaround: Rename the view variable to some other name