Android NavigationUI startDestination class (not ID) programmatically

陌路散爱 提交于 2020-03-04 18:56:49

问题


I need to set the start destination of a navigation graph programmatically depending on a condition. I have Fragment0, and also Fragment1, Fragment2, ... FragmentN all extending Fragment0, and being all of them (including Fragment0) able to be that wished start destination.

I already know there is the method from NavGraph called

setStartDestination(R.id.nav_fragment_X);

but it is not useful for me because, if I am not wrong, it requires to have all these fragment0...N nodes declared in the xml navigation file.

So, what I would like to, is to have just one fragment node in the xml file and be able to set, programmatically, the Class (a fragment in my case) that in normal cases you can indicate via the design/text tabs of android studio and is displayed like this:

    android:name="com.android.fragments.FragmentX"

回答1:


I finally ended up with the answer:

First you get your startDestination graph by, for instance, executing:

NavDestination startDestNode = navGraph.findNode(R.id.start_dest);

And, later, you update the class name by getting use of:

((FragmentNavigator.Destination) startDestNode).setClassName("Class name you wish");

In conclusion, the method setClassName(String className) of the class FragmentNavigator.Destination allows you to indicate the fragment class that will be displayed associated with the destination.



来源:https://stackoverflow.com/questions/59500752/android-navigationui-startdestination-class-not-id-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!