gpt4 book ai didi

java - 如何在 Android 中使用 Java 以编程方式构建 NavGraph

转载 作者:行者123 更新时间:2023-12-04 23:59:53 28 4
gpt4 key购买 nike

我知道用 XML 构建 NavGraph 很容易,但是如何用 java 代码实现呢?

没有“app:navGraph”属性的 fragment XML 定义:

<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(???));

问题:如何在这里创建一个新的 NavGraph 对象?哪个 navigatorClass 应该用作方法“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);
}

谢谢。

最佳答案

请在此处查看 java 代码:

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

关于java - 如何在 Android 中使用 Java 以编程方式构建 NavGraph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61885815/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com