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

Fragment间跳转时能否移除MainActivity的BottomNavigation Bar

问题根因

你当前的代码无法生效,是因为你在LoadFragment中调用inflater.inflate(R.layout.activity_main, container, false)加载出的是一个全新的、未挂载到当前界面的临时MainActivity布局实例,对这个实例里的控件做隐藏操作,完全不会影响屏幕上正在显示的、属于MainActivity实例的BottomNavigationView。

可行实现方案

方案1:单Fragment内直接控制(适合少量页面需要隐藏导航栏的场景)

不要自行inflate主布局,直接通过当前Fragment附着的宿主Activity获取已经在显示的导航栏控件即可,同时注意离开页面时恢复导航栏显示,避免其他关联页面出现导航栏异常消失的问题:

class LoadFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_load, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 直接获取宿主Activity中已挂载的底部导航栏
        val bottomNav = requireActivity().findViewById<BottomNavigationView>(R.id.bottom_home_navigation)
        bottomNav.visibility = View.GONE
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 页面销毁时恢复导航栏显示
        val bottomNav = requireActivity().findViewById<BottomNavigationView>(R.id.bottom_home_navigation)
        bottomNav.visibility = View.VISIBLE
    }
}

方案2:导航监听统一控制(推荐,适合多Fragment切换的场景)

如果你使用Android Jetpack Navigation组件做Fragment跳转,可以直接在MainActivity中监听导航目的地变化,统一管理底部导航栏的显隐,不需要在每个需要隐藏导航栏的Fragment中重复写逻辑:

// 在MainActivity的onCreate方法中添加如下配置
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_home_navigation)

navController.addOnDestinationChangedListener { _, destination, _ ->
    when(destination.id) {
        R.id.loadFragment -> bottomNav.visibility = View.GONE
        // 后续其他需要隐藏导航栏的FragmentId可直接在此处新增分支
        else -> bottomNav.visibility = View.VISIBLE
    }
}

注意:Fragment中只能操作已经附着到Window上的View实例,自行inflate宿主布局生成的独立View对象和当前显示界面没有关联,所有针对它的修改都不会同步到真实显示的界面上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 12:12:21