'How can I remove startDestination attribute from navigation_main?

navigation_main file

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

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

Is it possible to remove app:startDestination="@id/navigation_main_countries_fragment" from navigation_main file and do it programmatically? If the int x was 0 then run countries_fragment otherwise categories_fragment.

I'm using Java language.

Please test your answer before posting it because many people posted their answers but unfortunately the answers do not work.



Solution 1:[1]

The navigation documentation explains it pretty well on Conditional Navigation using navigation components.

Solution 2:[2]

Is it possible to remove app:startDestination="@id/navigation_main_countries_fragment" from navigation_main file

No.

and do it programmatically?

Yes. but you should override it.

You must define a dummy destination in the xmL and then change it in your code:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_graph"
    app:startDestination="@id/empty_fragment">

    <fragment
        android:id="@+id/empty_fragment"
        android:name="com.example.EmptyFragment"
        android:label="EmptyFragment" />
</navigation>
val targetDestination = if (x == 0)
    R.id.navigation_main_countries_fragment
else
    R.id.navigation_main_categories_fragment

val navController = ....
navController.graph = navController.graph.apply { startDestination = targetDestination }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Ndiritu
Solution 2 beigirad