Home > Enterprise >  Navigation graph open another fragment
Navigation graph open another fragment

Time:11-18

I have a simple application where I am trying to open another fragment on click of a button.

My 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/app_navigation"
    app:startDestination="@id/homeFragment">


    <fragment
        android:id="@ id/homeFragment"
        android:name="com.mine.parsexml.HomeFragment"
        android:label="fragment_home"
        tools:layout="@layout/fragment_home" >

        <action
            android:id="@ id/action_homeFragment_to_playerFragment"
            app:destination="@id/playerFragment" />
    </fragment>
    <fragment
        android:id="@ id/playerFragment"
        android:name="com.mine.parsexml.PlayerFragment"
        android:label="fragment_player"
        tools:layout="@layout/fragment_player" />
</navigation>

This is my onClick in fragment

binding.playVideos.setOnClickListener {
        HomeFragmentDirections.actionHomeFragmentToPlayerFragment()
    }

This is the activity layout

<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@ id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/app_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

When I click the button the player fragment doesn't open up.

CodePudding user response:

You must use NavController and use action id

@Override
  public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
  super.onViewCreated(view, savedInstanceState);
    
   NavController navController = Navigation.findNavController(view);
    
   binding.playVideos.setOnClickListener {
                
   navController.navigate(R.id.action_homeFragment_to_playerFragment);

}

CodePudding user response:

Although the accepted answer works; but I see that you already using safeArgs feature for navigation, so to fix that using safeArgs:

binding.playVideos.setOnClickListener {
    findNavController().navigate(
        HomeFragmentDirections.actionHomeFragmentToPlayerFragment()
    )
}

The advantage would appear much in case you send arguments to the new destination fragment.

  • Related