android 导航栏组件

Google introduced the Android Jetpack, which is a set of components, tools and architectural guidance that makes it quick and easy to build great Android apps. Amongst these components, is the Navigation Library — which handles everything concerning navigating throughout your application.

Google推出了Android Jetpack ,它是一组组件,工具和体系结构指南,可帮助您快速轻松地构建出色的Android应用程序。 在这些组件中,有一个导航库-处理整个应用程序中与导航有关的所有事情。

Before this addition from Google, navigation could be a source of pain during development and if not handled well could lead to unfavourable user experience.

在加入Google之前,导航可能是开发过程中的痛苦之源,如果处理不当可能会导致不利的用户体验。

Before going further, there are three key parts of android navigation:

在进一步介绍之前,Android导航包含三个关键部分:

  1. Navigation graph: this is an XML resource where you describe the flow of the application. This typically contains the individual fragments and activities called destinations.
    导航图:这是XML资源,您可以在其中描述应用程序的流程。 通常包含单个片段和称为目标的活动
  2. NavHost: This is an empty container that displays your destinations from your navigation graph. You can see it as a host for all your destinations.
  3. NavController: This is responsible for the swapping of destinations in the NavHost as the users move throughout your app.
    NavController:当用户在整个应用程序中移动时,它负责在NavHost中交换目的地。

(Lets get started..)

To use the android navigation component, we need to add the following dependencies to our app’s build.gradle file as below:

要使用android导航组件,我们需要将以下依赖项添加到应用程序的build.gradle文件中,如下所示:

def nav_version = "2.3.0"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

In our mainActivity’s layout file activity_main.xml , we make this activity our navHost, so we add a NavHostFragment to the layout file like this:

在mainActivity的布局文件activity_main.xml ,将此活动设为navHost,因此我们将NavHostFragment添加到布局文件中,如下所示:

activity_main.xml activity_main.xml

In the image above, we added three attributes to the activity_main.xml :

在上图中,我们向activity_main.xml添加了三个属性:

1. android:name contains the class name of your NavHost implementation.
 android:name包含NavHost实现的类名。 2. app:defaultNavHost="true" ensures that your NavHostFragment intercepts the system back button.
 app:defaultNavHost="true"确保您的NavHostFragment拦截系统后退按钮。 3. app:navGraph this attribute links the NavHostFragment with a navigation graph.
 app:navGraph此属性将NavHostFragment与导航图链接。

Remember the navigation graph we talked about earlier in this post, this is where we create it. In the res/ folder, create a directory named navigation , inside this folder create a xml file (name it anything) but for the purpose of this article, we name it nav_host.xml

记住我们在本文前面讨论的导航图,这是我们创建导航图的地方。 在res/文件夹中,创建一个名为navigation的目录,在该文件夹中创建一个xml文件(命名为任何文件),但出于本文的目的,我们将其命名为nav_host.xml

In this file, we include the two fragments needed for navigation. In this case, we have FragmentA and FragmentB ,

在此文件中,我们包含导航所需的两个片段。 在这种情况下,我们有FragmentAFragmentB

<?xml version="1.0" encoding="utf-8"?><navigation xmlns:android="http:///apk/res/android"
    xmlns:app="http:///apk/res-auto"
    xmlns:tools="http:///tools"
    android:id="@+id/nav_host"
    app:startDestination="@id/fragmentA">
    <fragment
        android:id="@+id/fragmentA"
        android:name="com.example.navigationtesting.FragmentA"
        android:label="fragment_a"
        tools:layout="@layout/fragment_a" />

    <fragment
        android:id="@+id/fragmentB"
        android:name="com.example.navigationtesting.FragmentB"
        android:label="fragment_b"
        tools:layout="@layout/fragment_b" />
</navigation>

In the snippet above, I made FragmentA the start destination. This would be the first fragment to be hosted in our activity_main.xml . It is the first screen the users would see when opening the activity.

在上面的代码段中,我将FragmentA为起始目标。 这将是我们的activity_main.xml托管的第一个片段。 这是用户在打开活动时看到的第一个屏幕。

(Connecting destinations….,)

Next we connect the destinations in our app, in this case we want to move from FragmentA to FragmentB . So in our nav_host.xml , open the design tab and connect both fragments by dragging the cursor from the design you want to navigate from to the fragment you are navigating to, in this case, we have two fragments so we are dragging the cursor from FragmentA to FragmentB like in the image below,

接下来,我们在应用程序中连接目标,在这种情况下,我们要从FragmentA移到FragmentB 。 因此,在我们的nav_host.xml ,打开设计选项卡,然后通过将光标从要导航的设计中拖动到要导航到的片段来连接两个片段,在这种情况下,我们有两个片段,因此要从中拖动光标如下图所示,从FragmentAFragmentB

Fragment A to Fragment B connection

片段A与片段B的连接

By doing so, we have some code generated in our code tab.

这样,我们在代码选项卡中生成了一些代码。

Introducing SafeArgs…

介绍SafeArgs…

One of the cool things introduced in Android Navigation is the Safe Args plugin, this plugin generates code that contains classes and methods for each action you have defined. In this example, since we want to navigate from the FragmentA to FragmentB , a class would be generated called FragmentADirections . This class contains a static method for each action defined in the originating destination.

Android导航中引入的很酷的功能之一是Safe Args插件,该插件会生成代码,其中包含您已定义的每个操作的类和方法。 在此示例中,由于我们要从FragmentA导航到FragmentB ,因此将生成一个名为FragmentADirections 。 此类为始发目标中定义的每个动作包含一个静态方法。

To include safeArgs in our app, we need to add the following dependencies;

为了在我们的应用程序中包含safeArgs ,我们需要添加以下依赖项;

add the line as a dependency in your top level build.gradle file:

顶层 build.gradle文件中添加该行作为依赖build.gradle

def nav_version = "2.3.0"classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"

Also, add the line below to the top of your app or module’s build.gradle

另外, build.gradle添加到应用或模块的 build.gradle build.gradle

apply plugin: "androidx.navigation.safeargs.kotlin"

Then rebuild your application, you would notice that you have the class FragmentADirections already created for you. With this, we can call the method to navigate from this fragment to another.

然后重建您的应用程序,您会发现已经为您创建了FragmentADirections类。 这样,我们可以调用该方法从该片段导航到另一个片段。

In FragmentA , in our onViewCreated , we navigate from this fragment to FragmentB by the click of a button defined in its layout like in the image below:

FragmentAonViewCreated ,通过单击其布局中定义的按钮,我们可以将该片段导航到FragmentB ,如下图所示:

After describing the action, we call findNavController().navigate() to make the call to navigate from this fragment.

在描述了动作之后,我们调用findNavController().navigate()进行从该片段导航的调用。

TADAAAAAAA!!! 🥳 🎉 🎊 , we have accomplished the first task.

TADAAAAAAA !!! 🎊,我们已经完成了第一个任务。

But, what about in a case where we want to pass data from fragments?

但是,如果要传递片段中的数据怎么办?

(Passing Arguments)

Now that we have gotten the navigation part working, let’s pass data from FragmentA to FragmentB. We would send a text entered in the first fragment and display the text in the second fragment.

现在,导航部分已经开始工作,让我们将数据从FragmentA传递到FragmentB 。 我们将发送在第一个片段中输入的文本,并在第二个片段中显示该文本。

First, open nav_host.xml file, edit the file to allow FragmentB accept arguments, since we are passing a string we would have this:

首先,打开nav_host.xml文件,编辑该文件以允许FragmentB接受参数,因为我们要传递一个字符串,所以我们需要这样:

<fragment
    android:id="@+id/fragmentB"
    android:name="com.example.navigationtesting.FragmentB"
    android:label="fragment_b"
    tools:layout="@layout/fragment_b" >
    <argument
        android:name="name"
        app:argType="string" />
</fragment>

Here, we are saying that FragmentB should expect an argument of type String.

在这里,我们说FragmentB应该期望一个String类型的参数。

Now, we go back to the FragmentA and you would notice that the static method is expecting an argument and we would pass our string gotten from the edit text like below:

现在,我们回到FragmentA ,您会注意到静态方法需要一个参数,并且将通过编辑文本获取的字符串传递如下:

Now we go back to the Fragment B to set the string gotten as an argument.

现在,我们返回到片段B,将获取的字符串设置为参数。

Note: you might get this error when trying to call navArgs()

注意:尝试调用navArgs()时可能会收到此错误

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper ‘-jvm-target’ option
 Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option

To resolve this issue, in you app build.gradle file , include this:

要解决此问题,请在您的app build.gradle文件中包括以下内容:

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()}

(In conclusion,)

We are done with the basics of Android navigation, for more information, you can refer to the docs.

我们已经完成了Android导航的基础知识

翻译自: https:///@okonjiemmanuel/introduction-to-android-navigation-component-5815891f460

android 导航栏组件