You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fragment中使用NavigationUI.setupWithNavController绑定Toolbar菜单无法跳转问题

问题原因
  • 独立Toolbar的菜单点击事件未绑定Navigation处理逻辑:你直接在Toolbar的XML属性中通过app:menu指定了菜单,NavigationUI.setupWithNavController()默认不会自动接管这种直接绑定到Toolbar的菜单点击事件,默认只会处理通过onCreateOptionsMenu加载的Activity级菜单事件。
  • 导航图配置存在错误:你当前导航图中设置的startDestination是@id/userList,但你给出的导航图代码中并没有对应id的目的地节点,会导致导航图加载异常,影响后续跳转逻辑。
解决方法
  1. 先修正导航图配置,将startDestination修改为你实际需要作为初始页面的Fragment id,示例如下:
<navigation 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:id="@+id/user"
    app:startDestination="@id/fragmentA">
    <fragment
        android:id="@+id/fragmentA"/>
    <fragment
        android:id="@+id/fragmentB"/>
</navigation>
  1. 给Fragment内的Toolbar手动设置菜单点击回调,绑定Navigation跳转逻辑,修改你Fragment的onViewCreated代码如下:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    NavController navController = Navigation.findNavController(view);
    AppBarConfiguration appBarConfiguration =
            new AppBarConfiguration.Builder(navController.getGraph()).build();
    Toolbar toolbar = view.findViewById(R.id.toolbar);
    NavigationUI.setupWithNavController(
            toolbar, navController, appBarConfiguration);
    // 新增菜单点击绑定逻辑
    toolbar.setOnMenuItemClickListener(item -> {
        return NavigationUI.onNavDestinationSelected(item, navController);
    });
}
  1. 校验菜单项id与导航目的地id一致性:你当前代码中菜单item的android:id和导航图中对应Fragment的android:id是完全匹配的,符合NavigationUI的跳转要求,无需修改,后续调整id时保持一致即可。

内容的提问来源于stack exchange,提问作者Howard Lau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 19:57:03