我的主要问题是后退按钮(设备按钮)不能正常工作,因为...。findNavController().navigateUp()
是的。
我的结构如下。
主导航图。
Login -> Home, here FlowA and FlowB are loaded in DrawerLayout
HomeFragment代码:
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
private val viewModel: HomeViewModel by activityViewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val flow1Nav = NavHostFragment.create(R.navigation.flow_a)
val flow2Nav = NavHostFragment.create(R.navigation.flow_b)
childFragmentManager.beginTransaction()
.add(R.id.flContent, flow1Nav, flow1Nav.javaClass.name)
.add(R.id.flContent, flow2Nav, flow2Nav.javaClass.name)
.show(flow1Nav)
.hide(flow2Nav)
.commitNow()
binding.navView.findViewById<LinearLayout>(R.id.ll_flow1).setOnClickListener {
binding.drawerLayout.closeDrawers()
childFragmentManager.beginTransaction()
.show(flow1Nav)
.hide(flow2Nav)
.commit()
}
binding.navView.findViewById<LinearLayout>(R.id.ll_flow2).setOnClickListener {
binding.drawerLayout.closeDrawers()
childFragmentManager.beginTransaction()
.show(flow2Nav)
.hide(flow1Nav)
.commit()
}
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Use DrawerLayout as root container for activity -->
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="@+id/flContent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- Container for contents of drawer - use NavigationView to make configuration easier -->
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/drawer_header" />
<include layout="@layout/drawer_menu" />
</LinearLayout>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
流量A导航图
流程B导航图
findNavController().navigateUp()
按预期工作,而设备后退按钮不工作?所有的源码都可以找到 此处.
我找到了一个变通的方法
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
findNavController().navigateUp()
}