FragmentManager开始没有容器id的事务


fragmentManager.beginTransaction().replace(R.id.fragment_container_view,mapFragment).commit();

我们知道,这样我们可以加载或替换Fragment

在此snippet中,我们正在传递片段容器id。

有没有办法加载片段时不传递ID或不传递ID而传递FragmentContainerView

您可以使用导航图形操作在片段之间导航,像这样的一行代码:

Navigation.findNavController(this).navigate(R.id.action_fragment1_to_fragment2)

条件是:

  • 你有一个像这样的导航图
<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/nav_graph"
app:startDestination="@id/fragment_1">
<fragment
android:id="@+id/fragment_1"
android:name="Your.Package.Fragment_1"
tools:layout="@layout/fragment_1_layout">
<action
android:id="@+id/action_fragment1_to_fragment2"
app:destination="@id/fragment_2" />
</fragment>
<fragment
android:id="@+id/fragment_2"
android:name="Your.Package.Fragment_2"
tools:layout="@layout/fragment_2_layout">
</fragment>
</navigation>
  • 你已经写了正确的代码来设置你的活动与导航组件。

如果你不知道什么是导航组件,我强烈建议你在android开发者的导航实验室,它应该指导你如何设置你的项目。

Learn Jetpack Navigation | Android Developers (Java)

有关导航组件和片段的更多信息,请遵循这些链接并开始阅读Android开发者教程。

Fragments| Android Developers

导航组件| Android开发者

最新更新