我一直在关注 Navigation Architecture Component 的文档了解这个新的导航系统是如何工作的。
要从一个屏幕返回/返回另一个屏幕,您需要一个实现 NavHost
接口(interface)的组件。
The NavHost is an empty view whereupon destinations are swapped in and out as a user navigates through your app.
但是,目前似乎只有 Fragments 实现了 NavHost
The Navigation Architecture Component’s default NavHost implementation is NavHostFragment.
所以,我的问题是:
即使我有一个可以用
Activity
实现的非常简单的屏幕,为了使用这个新的导航系统,Fragment
也需要托管包含实际 View ?Activity
会在近期实现NavHost
接口(interface)吗?
--已更新--
根据 ianhanniballake 的回答,我了解每个 Activity 都包含自己的导航图。但是,如果我想使用导航组件从一个 Activity 转到另一个 Activity (替换“旧”startActivity
调用),我可以使用 activity destinations
。 activity destinations
是什么我不清楚,因为 docs for migration不赘述:
Separate Activities can then be linked by adding activity destinations to the navigation graph, replacing existing usages of startActivity() throughout the code base.
- 使用
ActivityNavigator
代替startActivity
有什么好处吗? - 使用导航组件时,从 Activity 中走出来的正确方法是什么?
最佳答案
导航图仅存在于单个 Activity 中。根据 Migrate to Navigation guide , <activity>
destinations 可用于从导航图中启动 Activity,但一旦启动第二个 Activity,它就与原始导航图完全分离(它可以有自己的图或只是一个简单的 Activity)。
您可以通过可视化编辑器(通过点击 + 按钮,然后在项目中选择一个 Activity )或手动添加 XML 将 Activity 目的地添加到导航图:
<activity
android:id="@+id/secondActivity"
android:name="com.example.SecondActivity" />
然后,您可以像使用任何其他目的地一样使用它来导航到该 Activity (即启动 Activity ):
Navigation.findNavController(view).navigate(R.id.secondActivity);
关于android - 导航架构组件 - Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50452359/