Search code examples
javaandroidandroid-fragmentsandroid-navigation-graph

How do one set an ID for a fragment displayed by a NavController and creating a Fragment object?


I created a navigation bar and ,I didn't understand how to create an ID for each fragment in grph.

navigation graph:

<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/nav_home">
    <fragment
        android:id="@+id/nav_home"
        android:name="com.mordechay.yemotapp.HomeFragment"
        android:label="fragment_home"
        tools:layout="@layout/fragment_home" >
    </fragment>
    <fragment
        android:id="@id/nav_explorer"
        android:name="com.mordechay.yemotapp.filseExplorerFragment"
        android:label="fragment_filse_explorer"
        tools:layout="@layout/fragment_filse_explorer" />
</navigation>

in the activity:

<fragment
    android:id="@+id/nvgv_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintTop_toBottomOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:defaultNavHost="true"
    app:navGraph="@navigation/nav_graph"
    />

And I wrote in the activity:

Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.nav_explorer);

It comes out null, what do I need to write to get the fragment?

I tried to get the fragment by writing the ID of the fragment found in the navigation graph. But I get null.


Solution

  • You've already set your id's => android:id="@+id/nav_home" and android:id="@+id/nav_explorer".

    At first, you need to declare your navigation controller.

    val navigationController = findNavController(R.id.nvgv_fragment)
    

    then you can check destination fragment with listener

    navigationController.addOnDestinationChangedListener { _, destination, _ ->
        if (destination.id == R.id.nav_explorer) {
            // whatever you want to do
        }
    }
    

    But, if you only need an instance of displayed fragment, you can find the answer here: Current fragment instance