将导航组件与多个活动一起使用

Using the Navigation component with multiple activities

在 Android 文档中,它指出:

The Navigation component is designed for apps that have one main activity with multiple fragment destinations. The main activity is associated with a navigation graph and contains a NavHostFragment that is responsible for swapping destinations as needed. In an app with multiple activity destinations, each activity has its own navigation graph.

这是否意味着您不能使用导航组件从一个 activity 导航到另一个?好像是这样。

第二个问题:如果我创建一个使用导航抽屉的应用程序,当您添加一个 activity 具有导航抽屉的默认代码已经包含用于管理来自一个抽屉项目的导航的代码给另一个。那么 Navigation 组件在这里也有点没用吗?

Google 是否希望我们只创建单个 activity 应用程序?

Does Google want us to be creating only single activity apps?

单一 activity 架构是您可以迈向的方向。不受Google的限制(只是推荐)。该架构有其自身的优点和缺点。您不必为了添加导航组件而撕毁整个应用程序。评估并决定这是否值得。

Does this mean that you cannot use the Navigation component to navigate from one activity to another

不,您可以使用导航组件来代替 startActivity 调用。只需将第二个 Activity 导航图添加到第一个 Activity 导航图,然后使用导航控制器在两者之​​间导航。

findNavController().navigate(directions)

这是它的迁移指南https://developer.android.com/guide/navigation/navigation-migrate#add

如果您想使用不同的 activity,您可以评估是否需要不同的 activity 或不同的任务。

If I create an app that uses the navigation drawer, the default code that created when you add an activity that is to have a navigation drawer already has code for managing navigation from one drawer item to another. So is the Navigation component also kind of useless here?

instead of using the default code for a navigation drawer to build your own navigation drawer that is more inline with the Navigation component

关键是您不必构建自定义组件或任何复杂的东西。实际上,使用导航组件(在 NavigationUI class 的帮助下)简化了抽屉布局及其侦听器的代码。

this link,该文档帮助您在使用导航抽屉和底部导航视图时实现导航组件。

关于生成的模板,那些已经过时,需要升级。

参考文献:

https://developer.android.com/guide/navigation/navigation-migrate https://developer.android.com/guide/navigation/navigation-ui

答案是 不需要.

Navigation Component idea中需要有1+3个parts和无限的fragments。

您可以观看Google Navigation Component Video.

只有一个Activity.

  1. 单身Activity

这些在 Activity 中工作(Single Activity)。

  1. 导航图
  2. NavHostFragment
  3. 导航控制器

Why Unnecessary? Because, all parts of "1 + 3" connected with each other.

Details: Navigation graph is connected with NavFostFragment. Moreover, NavFostFragment defines in XML file of Single Activity. Also, NavController defines by NavController as "navHostFragment.navController".

但是,如果你真的很想在Activity中使用Navigation Compenent,你需要在Activity中使用add fragments。

例如:

[Activity_A + Fragment_A] 和 [Activity_B + Fragment_B]

The idea of solution is:

For Activity_A to Activity_B: Navigate Fragment_A -> Activity_B

OR

You can migrate. For Activity_A to Activity_B: Navigate Fragment_A -> Activity_B

More detail: Migrate to the Navigation component by Google