异常日志:
java.lang.IllegalArgumentException: Navigation action/destination com.xxx.xxx:id/action_AFragnebt_to_BFragment cannot be found from the current destination Destination(com.xxx.xxx:id/BFragment) label=BFragment class=com.XXX.XXX.ui.fragment.setting.BFragment
at androidx.navigation.NavController.navigate(NavController.java:938)
at androidx.navigation.NavController.navigate(NavController.java:875)
at androidx.navigation.NavController.navigate(NavController.java:861)
at androidx.navigation.NavController.navigate(NavController.java:849)
at com.XXX.XXX.ui.fragment.delivery.AFragment.onClickListener(AFragment.kt:290)
at android.view.View.performClick(View.java:7259)
at android.view.View.performClickInternal(View.java:7236)
at android.view.View.access$3600(View.java:801)
at android.view.View$PerformClick.run(View.java:27896)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7397)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
异常日志对应代码:
com.xxx.xxx:id/action_AFragnebt_to_BFragment cannot be found from the current destination Destination(com.xxx.xxx:id/BFragment)
从代码看跳转的时候是在BFragment中调用的NavHostFragment.findNavController(this).navigate(R.id.action_AFragnebt_to_BFragment)进行的页面跳转,而从异常日志却提示的是BFragment中没查找到这个action,为何是从BFragment查找而不是实际跳转位置的AFragment ?
开始分析源码:
先分析NavHostFragment.findNavController(this)是如何获取到的NavController对象
NavHostFragment.java
@NonNull
public static NavController findNavController(@NonNull Fragment fragment) {
Fragment findFragment = fragment;
//如果当前fragment或者其parentFragment有继承了NavHostFragment的话就直接获取对应的NavController
while (findFragment != null) {
if (findFragment instanceof NavHostFragment) {
return ((NavHostFragment) findFragment).getNavController();
}
Fragment primaryNavFragment = findFragment.getParentFragmentManager()
.getPrimaryNavigationFragment();
if (primaryNavFragment instanceof NavHostFragment) {
return ((NavHostFragment) primaryNavFragment).getNavController();
}
findFragment = findFragment.getParentFragment();
}
// Try looking for one associated with the view instead, if applicable
//我们的AFragment和BFragment都没有继承NavHostFragment,实际走下面逻辑
View view = fragment.getView();
if (view != null) {
return Navigation.findNavController(view);
}
// For DialogFragments, look at the dialog's decor view
Dialog dialog = fragment instanceof DialogFragment
? ((DialogFragment) fragment).getDialog()
: null;
if (dialog != null && dialog.getWindow() != null) {
return Navigation.findNavController(dialog.getWindow().getDecorView());
}
throw new IllegalStateException("Fragment " + fragment
+ " does not have a NavController set");
}
从上面NavHostFragment源码可以分析出最终走了Navigation.findNavController(view)获取NavController。
Navigation.java
@NonNull
public static NavController findNavController(@NonNull View view) {
NavController navController = findViewNavController(view);
if (navController == null) {
throw new IllegalStateException("View " + view + " does not have a NavController set");
}
return navController;
}
@Nullable
private static NavController findViewNavController(@NonNull View view) {
//从view以及view的parentView中获取
while (view != null) {
NavController controller = getViewNavController(view);
if (controller != null) {
return controller;
}
ViewParent parent = view.getParent();
view = parent instanceof View ? (View) parent : null;
}
return null;
}
@Nullable
private static NavController getViewNavController(@NonNull View view) {
//从view的tag中获取
Object tag = view.getTag(R.id.nav_controller_view_tag);
NavController controller = null;
if (tag instanceof WeakReference) {
controller = ((WeakReference<NavController>) tag).get();
} else if (tag instanceof NavController) {
controller = (NavController) tag;
}
return controller;
}
从上面源码可以看出,最终是通过fragment中的view,或者parentView的一个R.id.nav_controller_view_tag的tag中拿到的NavController,而在NavHostFragment的onCreate中new了一个NavHostController,并在onViewCreate中为其布局view添加了tagR.id.nav_controller_view_tag传入了这个NavHostController对象
NavHostFragment.java
@CallSuper
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
final Context context = requireContext();
mNavController = new NavHostController(context);
.....................
super.onCreate(savedInstanceState);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (!(view instanceof ViewGroup)) {
throw new IllegalStateException("created host view " + view + " is not a ViewGroup");
}
Navigation.setViewNavController(view, mNavController);
// When added programmatically, we need to set the NavController on the parent - i.e.,
// the View that has the ID matching this NavHostFragment.
if (view.getParent() != null) {
mViewParent = (View) view.getParent();
if (mViewParent.getId() == getId()) {
Navigation.setViewNavController(mViewParent, mNavController);
}
}
}
//Navigation中的setViewNavController()
public static void setViewNavController(@NonNull View view,
@Nullable NavController controller) {
//通过R.id.nav_controller_view_tag传入了controller
view.setTag(R.id.nav_controller_view_tag, controller);
}
而AFragment和BFragment对应的同一个activity布局如下,最终获取到的是设置的同一个NavHostFragment中的NavController。
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fmContainer"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/navigation_XX_task"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
接下来分析的navigate跳转:
如果在AFragment连续调用两次navigate(R.id.action_AFragment_to_BFragment),当第一次的跳转数据加入到mBackStack后,再次调用一次navigate(R.id.action_AFragment_to_BFragment)。
public void navigate(@IdRes int resId, @Nullable Bundle args, @Nullable NavOptions navOptions,
@Nullable Navigator.Extras navigatorExtras) {
//如果mBackStack栈不是空就获取最后的加入的NavDestination,
//当第一次跳转后mBackStack.getLast().getDestination()对应的是BFragment的NavDestination
NavDestination currentNode = mBackStack.isEmpty()
? mGraph
: mBackStack.getLast().getDestination();
if (currentNode == null) {
throw new IllegalStateException("no current navigation node");
}
//destId=R.id.action_AFragment_to_BFragment
@IdRes int destId = resId;
//在BFragment的NavDestination中没有R.id.action_AFragment_to_BFragment
//此时navAction==null
final NavAction navAction = currentNode.getAction(resId);
Bundle combinedArgs = null;
if (navAction != null) {
if (navOptions == null) {
navOptions = navAction.getNavOptions();
}
destId = navAction.getDestinationId();
Bundle navActionArgs = navAction.getDefaultArguments();
if (navActionArgs != null) {
combinedArgs = new Bundle();
combinedArgs.putAll(navActionArgs);
}
}
..................................
//此处返回的node==null
NavDestination node = findDestination(destId);
if (node == null) {
final String dest = NavDestination.getDisplayName(mContext, destId);
if (navAction != null) {
throw new IllegalArgumentException("Navigation destination " + dest
+ " referenced from action "
+ NavDestination.getDisplayName(mContext, resId)
+ " cannot be found from the current destination " + currentNode);
} else {
//navAction为null 走这边
throw new IllegalArgumentException("Navigation action/destination " + dest
+ " cannot be found from the current destination " + currentNode);
}
}
navigate(node, combinedArgs, navOptions, navigatorExtras);
}
@SuppressWarnings("WeakerAccess") /* synthetic access */
NavDestination findDestination(@IdRes int destinationId) {
//destinationId==R.id.action_AFragment_to_BFragment
if (mGraph == null) {
return null;
}
if (mGraph.getId() == destinationId) {
return mGraph;
}
//第二次跳转时 currentNode 对应的是BFragment的NavDestination
NavDestination currentNode = mBackStack.isEmpty()
? mGraph
: mBackStack.getLast().getDestination();
NavGraph currentGraph = currentNode instanceof NavGraph
? (NavGraph) currentNode
: currentNode.getParent();
//从BFragment的Graph中没有 R.id.action_AFragment_to_BFragment
//返回null
return currentGraph.findNode(destinationId);
}
结论:通过代码分析如果在AFragment执行一次到BFragment的跳转后,一定的情况下(已经跳到BFragment并将BFragment加入到BackStack队列中后) 再次执行从A到B的跳转就会出现上述异常崩溃。
简单粗暴的解决方案
//将navigate这一步加上try catch,防止出现上述崩溃
fun NavController.navigateSafe(resId: Int, args: Bundle?=null,navOptions : NavOptions?=null) {
try {
navigate(resId, args,navOptions)
} catch (e: Exception) {
Pdlog.d("NavigationExt","navigate: resId = $resId args = $args")
Pdlog.d("NavigationExt","navigate: "+e)
}
}
其他解决思路:
//调用navigate跳转之前先判断
if (navController.currentDestination?.id == R.id.Afragment) {
navController.navigate(R.id.action_Afragment_to_Bfragment)
}