1

How can I add startDestination programmatically according the value for example if the integer variable was 0 then I want to start navigation_main_countries_fragment, Otherwise navigation_main_categories_fragment.

Inside activity_main

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/activity_main_container"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:navGraph="@navigation/navigation_main" //I deleted this line already
    android:layout_weight="1" />

Inside navigation_main

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@id/navigation_main_countries_fragment" //I deleted this line already
    tools:ignore="InvalidNavigation">

    <fragment
        android:id="@+id/navigation_main_countries_fragment"
        android:name="com.test.app.fragments.CountriesFragment"
        tools:layout="@layout/fragment_countries" />

    <fragment
        android:id="@+id/navigation_main_categories_fragment"
        android:name="com.test.app.fragments.CategoriesFragment"
        tools:layout="@layout/fragment_categories" />

</navigation>
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Taha Sami
  • 1,565
  • 1
  • 16
  • 43
  • 1
    Does this answer your question? [How to change start destination of a navigation graph programmatically \[Jetpack\]](https://stackoverflow.com/questions/51173002/how-to-change-start-destination-of-a-navigation-graph-programmatically-jetpack) – Phil Dukhov Feb 10 '22 at 09:18
  • @PhilipDukhov All answers in Kotlin but I want in Java – Taha Sami Feb 10 '22 at 09:33

2 Answers2

0

Try this code

// Configure the navigation
val navHost = nav_host_fragment as NavHostFragment
graph = navHost.navController.navInflater.inflate(R.navigation.nav_graph)
if(value == 0)
graph.startDestination = R.id.counriesFragment
else
grapgh.startDestination = R.id.categoryFragment


navHost.navController.graph = graph

NavigationUI.setupActionBarWithNavController(this, navHost.navController)
Muhammad Asad
  • 694
  • 6
  • 10
0

You can use below code for start destination

val navHostFragment = (supportFragmentManager.findFragmentById(R.id.home_nav_fragment) as NavHostFragment)
val inflater = navHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.nav_main)
graph.startDestination = R.id.fragment1

navHostFragment.navController.graph = graph
Sumit Kumar
  • 263
  • 1
  • 6