【发布时间】:2020-05-19 07:48:43
【问题描述】:
我知道用 XML 构建 NavGraph 很容易,但是如何用 java 代码来实现呢?
不带“app:navGraph”属性的片段 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);
}
谢谢。
【问题讨论】:
-
感谢@Askar,该链接是使用 XML 定义扩展 NavGraph。我从“developer.android.com”找到了这个链接,但它使用 Kotlin 以编程方式而不是 Java 来构建 NavGraph。我不明白里面的 Kotlin 代码。请帮助检查并查看如何将其转换为 Java。谢谢。链接:developer.android.com/guide/navigation/navigation-kotlin-dsl
标签: java android navigation