导航组件提供以编程方式创建某些导航元素并与之交互的方法。
创建 NavHostFragment
您可以使用 NavHostFragment.create()
以编程方式创建具有特定图形资源的 NavHostFragment
,如下例所示:
Kotlin
val finalHost = NavHostFragment.create(R.navigation.example_graph) supportFragmentManager.beginTransaction() .replace(R.id.nav_host, finalHost) .setPrimaryNavigationFragment(finalHost) // this is the equivalent to app:defaultNavHost="true" .commit()
Java
NavHostFragment finalHost = NavHostFragment.create(R.navigation.example_graph); getSupportFragmentManager().beginTransaction() .replace(R.id.nav_host, finalHost) .setPrimaryNavigationFragment(finalHost) // this is the equivalent to app:defaultNavHost="true" .commit();
请注意,setPrimaryNavigationFragment(finalHost)
允许您的 NavHost
截获对系统“返回”按钮的按下操作。您也可以添加 app:defaultNavHost="true"
,在 NavHost
XML 中实现此行为。如果要实现自定义“返回”按钮行为,并且不希望 NavHost
截获对“返回”按钮的按下操作,您可以将 null
传递给 setPrimaryNavigationFragment()
。
使用 ViewModel 在目标间共享界面相关数据
从 2.1.0-alpha02 版本开始,您可以创建一个范围限定于导航图的 ViewModel
,从而使您能够在图表的目标间共享与界面相关的数据。以这种方式创建的任何 ViewModel
对象都会一直存在,直至关联的 NavHost
及其 ViewModelStore
遭到清除,或导航图从返回栈中弹出为止。
以下示例展示如何检索范围限定于导航图的 ViewModel
:
Kotlin
在 Kotlin 中,您可以使用 navGraphViewModels()
属性委托从 Fragment 目标中检索 ViewModel
:
val factory: ViewModelProviderFactory = ... val viewModel: MyViewModel by navGraphViewModels(R.id.my_graph) { factory }
请注意,在此示例中,by navGraphViewModels()
会自动调用 findNavController()
来检索关联的 NavController
。
Java
ViewModelProviderFactory factory = ... ViewModelStoreOwner owner = navController.getViewModelStoreOwner(R.id.my_graph); MyViewModel viewModel = new ViewModelProvider(owner, factory);
如需了解有关 ViewModel
的详细信息,请参阅 ViewModel 概览。