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

使用NavController与BottomNavigationBar时Fragment重复重建导致GoogleMap重复初始化的问题咨询

我遇到了一个困扰很久的问题:我的Fragment A里嵌入了GoogleMap,当我通过底部导航栏切换到Fragment B,再切回Fragment A的时候,地图会被重新初始化;但如果是按返回键回到Fragment A,地图就能完美恢复到之前的状态,比如之前缩放的层级、定位的位置都还在。

下面是我相关的代码实现:

底部导航栏设置代码

private fun setupBottomNavigationBar() {
    val navHostFragment = supportFragmentManager.findFragmentById(R.id.navigationContainer) as NavHostFragment
    navHostFragment.navController.setGraph(R.navigation.main_graph)
    NavigationUI.setupWithNavController(binding.bottomNavigationBar, navHostFragment.navController)
    binding.bottomNavigationBar.setOnItemReselectedListener {
        // Do nothing to ignore the reselection
    }
}

说明:Fragment的切换逻辑完全是由Navigation组件自动处理的

导航图XML代码

<?xml version="1.0" encoding="utf-8"?>
<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/main_graph"
    app:startDestination="@id/home_graph">

    <include app:graph="@navigation/home_graph"/>
    <include app:graph="@navigation/captain_portal_graph"/>
    <include app:graph="@navigation/accounts_graph"/>

</navigation>

所有Fragment继承的BaseFragment代码

abstract class BaseFragment<TViewBinding : ViewDataBinding> : Fragment() {

    private var innerBinding: TViewBinding? = null
    protected val binding: TViewBinding get() = innerBinding ?: throw IllegalStateException("Trying to access the binding outside of the lifecycle.")

    abstract val layoutId: Int

    protected val baseActivity: BaseActivity<*>
        get() = activity as BaseActivity<*>

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        innerBinding = DataBindingUtil.inflate(inflater, layoutId, container, false)
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        setupActionBar()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        innerBinding = null
    }
}

我看Google官方的示例项目里,同样用Navigation+BottomNavigationBar的组合,切换Fragment时能保留之前的状态,不会重建Fragment。我对照着看了半天也没找出问题,有没有大佬能帮我看看我哪里写错了?

备注:内容来源于stack exchange,提问作者Mohsin Falak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 12:04:31