因此,我在片段A中有一个GoogleMap,每当我从底部导航栏中选择片段B并再次选择片段A时,Map会重新初始化。然而,如果我通过回按返回片段A,则mapview会恢复到先前的状态。
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
}
}
字符串
片段事务由NavigationWeb本身处理。
<?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>
型
我的fragments扩展了这个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的官方sample正在按预期工作,我想实现相同的行为,我做错了什么?
1条答案
按热度按时间bxgwgixi1#
在你的图中,定义你的导航操作,它会导致你的Map片段与
app:launchSingleTop="true"
。app:launchSingleTop
:此导航操作是否应作为单顶启动(即,返回堆栈顶部最多有一个给定目标的副本)来源:https://developer.android.com/reference/androidx/navigation/NavOptions
要让导航组件与正常的后退导航同步,你还必须将
app:defaultNavHost="true"
添加到你的片段容器视图中。app:defaultNavHost="true"
属性确保您的NavHostFragment拦截系统返回按钮。请注意,只有一个NavHost可以是默认值。如果您在同一布局中有多个主机(例如,双窗格布局),请确保仅指定一个默认NavHost。来源:https://developer.android.com/guide/navigation/get-started