所以我在片段A中有一个GoogleMap,每当我从BottomNavigationBar中选择片段B并再次选择片段A时,地图就会重新初始化。但是,如果我通过后按返回到片段 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
}
}
片段事务由 NavigationComponenet 本身处理。
<?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>
我的片段扩展了这个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 的官方样本正在按预期工作,我想实现相同的行为,我可能做错了什么?
在图表中使用
app:launchSingleTop="true"
定义导向地图片段的导航操作。
:此导航操作是否应作为单顶启动(即,返回堆栈顶部最多有一个给定目的地的副本)app:launchSingleTop
来源:https://developer.android.com/reference/androidx/navigation/NavOptions
要使导航组件与正常的后按导航同步,您还必须将
app:defaultNavHost="true"
添加到片段视图支架。
属性确保您的 NavHostFragment 拦截系统后退按钮。请注意,只能将一个 NavHost 设为默认值。如果同一布局中有多个主机(例如,两窗格布局),请务必仅指定一个默认 NavHost。app:defaultNavHost="true"
来源:https://developer.android.com/guide/navigation/get-started