5

I know it is easy to build a NavGraph with XML, but how to implement it with java code?

Fragment XML definition without "app:navGraph" attribute:

<fragment
    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:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
/>

<!-- app:navGraph="@navigation/mobile_navigation" -->

TestActivity.java

NavController navController = Navigation.findNavController(activity, R.id.nav_host_fragment);

// How to pass the Class argument into the getNavigator?
NavGraph navGraph = new NavGraph(navController.getNavigatorProvider().getNavigator(???));

Question: How to create a new NavGraph object here? Which navigatorClass should be used as the argument of method "getNavigator(Class)"?

androidx.navigation.NavigatorProvider.java

/**
 * Retrieves a registered {@link Navigator} using the name provided by the
 * {@link Navigator.Name Navigator.Name annotation}.
 *
 * @param navigatorClass class of the navigator to return
 * @return the registered navigator with the given {@link Navigator.Name}
 *
 * @throws IllegalArgumentException if the Navigator does not have a
 * {@link Navigator.Name Navigator.Name annotation}
 * @throws IllegalStateException if the Navigator has not been added
 *
 * @see #addNavigator(Navigator)
 */
@NonNull
public final <T extends Navigator<?>> T getNavigator(@NonNull Class<T> navigatorClass) {
    String name = getNameForNavigator(navigatorClass);
    return getNavigator(name);
}

Thanks.

2
  • stackoverflow.com/a/50899344/10735178 Commented May 19, 2020 at 8:12
  • 1
    Thanks @Askar, that link is inflate NavGraph with XML definition. I found this link from "developer.android.com" but it uses Kotlin to build NavGraph programmatically instead of Java. I don't understand with the Kotlin code inside. Please help to check and see how to convert it to Java. Thanks. The link: developer.android.com/guide/navigation/navigation-kotlin-dsl Commented May 19, 2020 at 8:29

1 Answer 1

3

Please see java code here:

NavHostFragment myNavHostFragment = (NavHostFragment) findViewById(R.id.my_nav_host_fragment);
NavInflater inflater = myNavHostFragment.getNavController().getNavInflater();
NavGraph graph = inflater.inflate(R.navigation.my_nav_graph);
myNavHostFragment.getNavController().setGraph(graph);
Sign up to request clarification or add additional context in comments.

1 Comment

Get it now. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.