android 如何在java中使用fragmentcontainerview?

5rgfhyps  于 2023-05-12  发布在  Android
关注(0)|答案(1)|浏览(262)

我在MainActivity中有一个这样的容器

<fragment
            android:id="@+id/main"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="5dp"
            android:paddingTop="5dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toTopOf="@+id/bottomNavigation"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/adView"
            app:navGraph="@navigation/main" />

在主要活动中这样使用它

FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.main, explorefragment);
   fragmentTransaction.commit();

它显示了这一点
将标记替换为FragmentContainerView。
我如何替换主活动的代码

f87krz0w

f87krz0w1#

<androidx.fragment.app.FragmentContainerView
            android:id="@+id/nav_host_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="androidx.navigation.fragment.NavHostFragment"
            app:defaultNavHost="true"
            app:navGraph="@navigation/main_screen_navigation"
            android:fitsSystemWindows="true"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

这就是你不需要写任何东西在主要活动
如果您使用它与底部导航然后

val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
     val navController = navHostFragment.navController
    binding.bnv.setupWithNavController(navController)

并确保底部导航视图中的导航目标ID和项目ID相同

在JAVA中

BottomNavigationView botoomNavigationView = binding.bnv;
    NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
    NavigationUI.setupWithNavController(botoomNavigationView, navHostFragment.getNavController());

相关问题