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

Android BottomNavigationDrawer模板下点击按钮切换fragment的问题

问题修正方案

你使用的BottomNavigationDrawer模板默认集成了Jetpack Navigation组件,原有代码的容器id选择和写法都存在问题,具体修正如下:

核心问题说明

你之前replace方法传入的R.id.container是整个页面根布局的id,如果直接替换这个容器,会把底部的导航栏也覆盖掉。专门承载所有子Fragment的容器id是R.id.nav_host_fragment_activity_main,对应你xml里的NavHostFragment节点。


方式1:继续使用原生FragmentTransaction(仅临时测试用,不推荐)

修正id和语法错误后代码如下:

// 注意getActivity是方法调用,需要加括号
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.nav_host_fragment_activity_main, new HomeFragment(), fragment.toString());
ft.addToBackStack(null);
ft.commit();

该写法会和Navigation组件的回退栈管理逻辑冲突,只适合临时调试使用。


方式2:使用Navigation组件原生API(官方推荐)

这套模板的所有Fragment都已经在res/navigation/mobile_navigation.xml的导航图中注册,直接用Navigation提供的跳转API即可,和模板的适配性更高:

  1. 先确认mobile_navigation.xml中HomeFragment已经注册,且有对应的id(如R.id.homeFragment)
  2. 按钮点击逻辑修改为:
// 参数view为点击的按钮实例
NavController navController = Navigation.findNavController(view);
// 传入导航图中HomeFragment对应的id即可完成跳转
navController.navigate(R.id.homeFragment);

如果需要配置跳转动画、自定义回退栈行为、传递参数,可以在导航图中新增对应的跳转action,调用navController.navigate(R.id.action_当前Fragment_id_to_HomeFragment)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:42:01