我知道用XML构建NavGraph很容易,但是如何用java代码实现它呢?
片段XML定义,没有“app:导航图”属性:
@+id/nav_host_片段“android:name="androidx.navigation.fragment.NavHostFragment”android:layout_width="match_parent“android:layout_height="match_parent”app:defaultNavHost=“真”app:layout_constraintLeft_toLeftOf=“父”app:layout_constraintRight_toRightOf=“父”app:layout_constraintTop_toTopOf=“父”/>“
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(类)”方法的参数?
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);
}谢谢。
发布于 2020-05-19 08:50:49
请参阅这里的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);https://stackoverflow.com/questions/61885815
复制相似问题