我知道用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" -->
测试活动.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(???));
问题: 如何在此处创建新的导航图对象? 哪个 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);