Search code examples
javaandroidfragmentfragmentmanagerfragmenttransaction

How to use fragmentcontainerview in java?


I have a container inside MainActivity like that

<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" />

and use it like that in main activity

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

It shows this

Replace the tag with FragmentContainerView.

how can i replace the code on main activity


Solution

  • <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" />
    

    that's it u don't need to write anything in main activity

    if ur using it with bottom navigation then

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

    and make sure that navigation destination id and items id in bottom navigation view are same

    in JAVA

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