博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android中的NavigationView
阅读量:2532 次
发布时间:2019-05-11

本文共 20338 字,大约阅读时间需要 67 分钟。

In this tutorial, we’ll discuss and implement a NavigationView in our android application. Here, we’ll learn to style it such that it opens from right to left too.

在本教程中,我们将在我们的android应用程序中讨论和实现NavigationView。 在这里,我们将学习如何设置样式,使其也从右向左打开。

导航视图 (NavigationView)

We have already implemented a Navigation Drawer in tutorial and it was tiresome to code.

我们已经在教程中实现了导航抽屉,并且编写代码很麻烦。

NavigationView is a better and easier to implement alternative to a Navigation Drawer. NavigationDrawer required us to implement the items using a / by implementing a custom Adapter.

NavigationView是一种更好,更容易实现的导航抽屉替代品。 NavigationDrawer要求我们通过实现自定义适配器来使用 / 实现项目。

With the introduction of a NavigationView all we require is to inflate the items using menu resources that we’ll see soon. NavigationView is generally placed inside a DrawerLayout.

随着NavigationView的引入,我们所要做的就是使用我们将很快看到的菜单资源来为项目充气。 NavigationView通常放置在DrawerLayout中。

NavigationView入门 (NavigationView Getting Started)

Android Studio provides us a ready made Navigation Drawer Activity that implements a standard Navigation Menu. You can choose it from the following dialog.

Android Studio为我们提供了一个现成的导航抽屉活动,该活动实现了一个标准的导航菜单。 您可以从以下对话框中选择它。

了解NavigationView (Understanding the NavigationView)

The NavigationView class extends FrameLayout. It’s defined in the xml under the tag as:

NavigationView类扩展了FrameLayout。 在标记下的xml中定义为:

The NavigationView essentially consists of two major components:

NavigationView本质上包含两个主要组件:

  1. HeaderView : This View is typically displayed at the top of the Navigation Drawer. It essentially holds the profile picture, name email address and a background cover pic. This view is defined in a separate layout file that we’ll look at in a bit. To add the layout into our NavigationView, the app:headerLayout parameter is used

    HeaderView :此视图通常显示在导航抽屉的顶部。 它实际上包含个人资料图片,姓名电子邮件地址和背景封面图片。 此视图是在一个单独的布局文件中定义的,我们将稍后介绍。 要将布局添加到NavigationView中,请使用app:headerLayout参数
  2. Menu : This is displayed below the HeaderView and it contains all the navigation items in the form of a list. The layout file for this is defined in the menus folder. To add the layout into the NavigationView , the app:menus parameter is used

    菜单 :此菜单显示在HeaderView下方,并且包含列表形式的所有导航项。 布局文件在menus文件夹中定义。 要将布局添加到NavigationView中,请使用app:menus参数

Other important XML attributes that are used to customise the NavigationView are:

用于自定义NavigationView的其他重要XML属性包括:

  1. app:itemTextColor : This changes the text color

    app:itemTextColor :这会更改文本颜色
  2. app:itemIconTint : This changes the icon color

    app:itemIconTint :这会更改图标颜色
  3. app:itemBackground : This changes the item background color

    app:itemBackground :这会更改项目背景颜色

Let’s look into the Project Structure of the inbuilt NavigationView template.

让我们看一下内置的NavigationView模板的项目结构。

The activity_main.xml is the layout for the MainActivity.

activity_main.xml是MainActivity的布局。

Note: The above DrawerLayout is the layout that holds the navigation drawer content and our app’s content.

注意 :上面的DrawerLayout是用于保存导航抽屉内容和我们应用程序内容的布局。

The app_bar_main.xml layout consists of a CoordinatorLayout that holds a ToolBar, a FloatingActionButton and a content_main.xml layout(which displays a basic ‘Hello World’ TextView). The layouts are listed below.

app_bar_main.xml布局由一个CoordinatorLayout和一个content_main.xml布局组成,该CoordinatorLayout包含一个工具栏,一个FloatingActionButton和一个content_main.xml布局(显示基本的“ Hello World” TextView)。 布局在下面列出。

app_bar_main.xml

app_bar_main.xml

The content_main.xml layout is listed below:

下面列出了content_main.xml布局:

The default headerLayout and the menu for the NavigationView are listed below:

下面列出了默认的headerLayout和NavigationView的菜单:

nav_header_main.xml

nav_header_main.xml

activity_main_drawer.xml

activity_main_drawer.xml

The android:checkableBehavior xml attribute is defined for the entire group and it takes either of the three values listed below.

android:checkableBehavior xml属性是为整个组定义的,它采用下面列出的三个值之一。

  1. single : Only one item from the group can be checked

    单人 :只能检查组中的一项
  2. all : All items can be checked (checkboxes)

    全部 :可以选中所有项目(复选框)
  3. none : No items are checkable

    :没有项目可检查

The android:checkable attribute is used for setting the checkable behaviour for individual items. It accepts boolean values.

android:checkable属性用于设置单个项目的可检查行为。 它接受布尔值。

Note: Nested menu items are possible inside the app:menus layout

注意 :在应用程序:菜单布局中可以使用嵌套菜单项

The MainActivity.java is given below

MainActivity.java在下面给出

package com.journaldev.navigationviewstyling;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.view.View;import android.support.design.widget.NavigationView;import android.support.v4.view.GravityCompat;import android.support.v4.widget.DrawerLayout;import android.support.v7.app.ActionBarDrawerToggle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.Menu;import android.view.MenuItem;public class MainActivity extends AppCompatActivity        implements NavigationView.OnNavigationItemSelectedListener {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);        //drawer.setDrawerListener(toggle);        drawer.addDrawerListener(toggle);        toggle.syncState();        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);        navigationView.setNavigationItemSelectedListener(this);    }    @Override    public void onBackPressed() {        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);        if (drawer.isDrawerOpen(GravityCompat.START)) {            drawer.closeDrawer(GravityCompat.START);        } else {            super.onBackPressed();        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }    @SuppressWarnings("StatementWithEmptyBody")    @Override    public boolean onNavigationItemSelected(MenuItem item) {        // Handle navigation view item clicks here.        int id = item.getItemId();        if (id == R.id.nav_camera) {            // Handle the camera action        } else if (id == R.id.nav_gallery) {        } else if (id == R.id.nav_slideshow) {        } else if (id == R.id.nav_manage) {        } else if (id == R.id.nav_share) {        } else if (id == R.id.nav_send) {        }        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);        drawer.closeDrawer(GravityCompat.START);        return true;    }}

Important inferences drawn from the above piece of code are given below:

从以上代码中得出的重要推论如下:

  1. The MainActivity implements NavigationView.OnNavigationItemSelectedListener and overrides the method onNavigationItemSelected. We handle the menu item clicks here and close the Drawer towards the left. Let’s display a Toast message for each of the items as show below.
    @Override    public boolean onNavigationItemSelected(MenuItem item) {        int id = item.getItemId();        if (id == R.id.nav_camera) {            // Handle the camera action            Toast.makeText(getApplicationContext(), "Camera is clicked", Toast.LENGTH_SHORT).show();        } else if (id == R.id.nav_gallery) {            Toast.makeText(getApplicationContext(), "Gallery is clicked", Toast.LENGTH_SHORT).show();        } else if (id == R.id.nav_slideshow) {            Toast.makeText(getApplicationContext(), "Slideshow is clicked", Toast.LENGTH_SHORT).show();        } else if (id == R.id.nav_manage) {            Toast.makeText(getApplicationContext(), "Tools is clicked", Toast.LENGTH_SHORT).show();                    } else if (id == R.id.nav_share) {            Toast.makeText(getApplicationContext(), "Share is clicked", Toast.LENGTH_SHORT).show();                    } else if (id == R.id.nav_send) {            Toast.makeText(getApplicationContext(), "Send is clicked", Toast.LENGTH_SHORT).show();                    }        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);        drawer.closeDrawer(GravityCompat.START);        return true;    }

    MainActivity实现NavigationView.OnNavigationItemSelectedListener并重写onNavigationItemSelected方法。 我们在这里处理菜单项的单击,然后向左关闭抽屉。 让我们为每个项目显示一条Toast消息,如下所示。
  2. The ActionBarDrawerToggle is initialised as:
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

    The ActionBarDrawerToggle is used with a DrawerLayout to implement the recommended functionality of Navigation Drawers. It has the following usages:

    • It acts as a listener, for opening and closing of drawers.
    • It provides the hamburger icons in the ToolBar/ActionBar.
    • It’s allows for the animation between the hamburger icon and the arrow to exist.

    Note: android.support.v4.app.ActionBarDrawerToggle is deprecated. Always use android.support.v7.app.ActionBarDrawerToggle as a replacement.

    ActionBarDrawerToggle初始化为:

    ActionBarDrawerToggle与DrawerLayout一起使用,以实现推荐的导航抽屉功能。 它具有以下用法:

    • 它充当打开和关闭抽屉的听众。
    • 它在ToolBar / ActionBar中提供汉堡包图标。
    • 允许在汉堡图标和箭头之间存在动画。

    注意android.support.v4.app.ActionBarDrawerToggle已弃用。 始终使用android.support.v7.app.ActionBarDrawerToggle进行替换。

  3. To add a listener on the DrawerLayout the following method is used.
    drawer.addDrawerListener(toggle);
    This listener is used to keep notified of drawer events.

    Note: drawer.setDrawerListener(toggle) is now deprecated.

    drawer.addDrawerListener(toggle);
    该侦听器用于使抽屉事件保持通知状态。

    注意 :不推荐使用drawer.setDrawerListener(toggle)。

  4. toggle.syncState() : will synchronise the icon’s state and display the hamburger icon or back arrow depending on whether the drawer is closed or open. Omitting this line of code won’t change the back arrow to the hamburger icon when the drawer is closed.

    toggle.syncState() :将同步图标的状态并显示汉堡图标或后退箭头,具体取决于抽屉是关闭还是打开。 关闭抽屉时,省略此行代码不会将后退箭头更改为汉堡包图标。
  5. drawer.closeDrawer(GravityCompat.START) : is used to close the drawer by setting the gravity to START(left by default)

    cabinet.closeDrawer(GravityCompat.START) :用于通过将重力设置为START来关闭抽屉(默认为左侧)

Here’s how the default NavigationView looks like in an application:

这是默认的NavigationView在应用程序中的外观:

Note that the last clicked item always stays highlighted in the first group. To remove the highlight as soon as the drawer is closed change the android:checkableBehavior to “none”.

请注意,最后单击的项目始终在第一组中保持突出显示。 要在抽屉关闭后立即移除高亮显示,请将android:checkableBehavior更改为“ none”。

The current NavigationView is drawn over the status bar. To put it beneath the status bar set the android:fitsSystemWindows as “false” for the NavigationView.

当前的NavigationView绘制在状态栏上。 要将其置于状态栏下方,请将NavigationView的android:fitsSystemWindows设置为“ false”。

Now with the above attributes set we can further style the NavigationView by putting it under the ToolBar/ActionBar(Though this is not recommended in the Material Design Guidelines) by setting android:layout_marginTop=”?attr/actionBarSize” in the NavigationView and also setting android:fitsSystemWindows=”false” for CoordinatorLayout and DrawerLayout.

现在,通过设置以上属性,我们可以通过在NavigationView中设置android:layout_marginTop =”?attr / actionBarSize”并将其设置在ToolBar / ActionBar(尽管在《材料设计准则》中不建议这样做)来进一步设置NavigationView的样式。 android:fitsSystemWindows =” false”用于CoordinatorLayout和DrawerLayout。

With the above customisation done, this is how the output looks :

完成上述自定义后,这就是输出的样子:

You see the white status bar at the top? It’s due to the android:fitSystemWindows set to false for CoordinatorLayout and the DrawerLayout.

Styling the status bar in the styles.xml like
@color/colorPrimaryDark won’t change it. We need a better approach.

您在顶部看到白色的状态栏吗? 这是由于android:fitSystemWindows对于CoordinatorLayout和DrawerLayout设置为false所致。

在styles.xml中样式化状态栏,例如
@color/colorPrimaryDark不会更改它。 我们需要更好的方法。

The only alternative is to get rid of the CoordinatorLayout (we aren’t using it’s animation either) and to put the DrawerLayout and ToolBar inside a LinearLayout.

唯一的选择是摆脱CoordinatorLayout(我们也不使用它的动画),并将DrawerLayout和ToolBar放在LinearLayout中。

Here are the update xml layouts:

这是更新xml布局:

activity_main.xml

activity_main.xml

android:fitSystemWindows=”true” is necessary in the Toolbar. Omitting it, you’ll end up with something like this!

工具栏中需要android:fitSystemWindows =“ true” 。 省略它,您将得到类似这样的结果!

Note: Removing the xml attribute android:theme="@style/AppTheme.AppBarOverlay" would change the ToolBar items color to black. Give it a go!

注意:删除xml属性android:theme="@style/AppTheme.AppBarOverlay"会将ToolBar项目颜色更改为黑色。 搏一搏!

app_bar_main.xml

app_bar_main.xml

This is how the application looks now.

这就是应用程序现在的外观。

Oh wait! The status bar color is identical with the ToolBar. It was supposed to be a shade darker.

Solution:
Just remove the following line from v-21/styles.xml

等一下! 状态栏颜色与工具栏相同。 本来应该是阴影深一点。

解:
只需从v-21 / styles.xml中删除以下行

@android:color/transparent

Let’s customise the NavigationView such that it opens from right to left!

让我们自定义NavigationView,使其从右向左打开!

项目结构 (Project Structure)

We’ll be adding our own hamburger icon png file into the drawable folder as shown below.

我们将自己的汉堡包图标png文件添加到drawable文件夹中,如下所示。

Android NavigationView示例代码 (Android NavigationView Example Code)

The activity_main.xml layout is now defined as

现在将activity_main.xml布局定义为

We’ve placed the ToolBar with a FrameLayout inside a RelativeLayout. android:fitSystemWindows needs to be set true in all three of them.

我们已经将带有BarLayout的ToolBar放置在RelativeLayout中。 android:fitSystemWindows必须在所有三个中都设置为true。

The DrawerLayout contains tools:openDrawer="end" and android:layout_gravity="end" which changes the default side of the drawer to right.

DrawerLayout包含tools:openDrawer="end"android:layout_gravity="end" ,它们将抽屉的默认面更改为右侧。

Ideally a circular header image looks beautiful inside a NavigationView. We’ll compile the dependency de.hdodenhof.circleimageview.CircleImageView and use that in our nav_header_main.xml file as shown below.

理想情况下,圆形标题图像在NavigationView中看起来很漂亮。 我们将编译依赖项de.hdodenhof.circleimageview.CircleImageView并将其用于我们的nav_header_main.xml文件中,如下所示。

nav_header_main.xml

nav_header_main.xml

The other xml layouts are identical to what were discussed above.

其他xml布局与上面讨论的相同。

The MainActivity.java is given below

MainActivity.java在下面给出

package com.journaldev.navigationviewtyling;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.view.View;import android.support.design.widget.NavigationView;import android.support.v4.view.GravityCompat;import android.support.v4.widget.DrawerLayout;import android.support.v7.app.ActionBarDrawerToggle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.MenuItem;import android.widget.Toast;public class MainActivity extends AppCompatActivity        implements NavigationView.OnNavigationItemSelectedListener {    DrawerLayout drawer;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);        findViewById(R.id.drawer_button).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // open right drawer                if (drawer.isDrawerOpen(GravityCompat.END)) {                    drawer.closeDrawer(GravityCompat.END);                }                else                drawer.openDrawer(GravityCompat.END);            }        });        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);        toggle.setDrawerIndicatorEnabled(false);        drawer.addDrawerListener(toggle);        toggle.syncState();        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);        navigationView.setNavigationItemSelectedListener(this);    }    @Override    public void onBackPressed() {        if (drawer.isDrawerOpen(GravityCompat.END)) {            drawer.closeDrawer(GravityCompat.END);        } else {            super.onBackPressed();        }    }        @SuppressWarnings("StatementWithEmptyBody")    @Override    public boolean onNavigationItemSelected(MenuItem item) {        // Handle navigation view item clicks here.        int id = item.getItemId();        if (id == R.id.nav_camera) {            // Handle the camera action            Toast.makeText(getApplicationContext(), "Camera is clicked", Toast.LENGTH_SHORT).show();        } else if (id == R.id.nav_gallery) {            Toast.makeText(getApplicationContext(), "Gallery is clicked", Toast.LENGTH_SHORT).show();        } else if (id == R.id.nav_slideshow) {            Toast.makeText(getApplicationContext(), "Slideshow is clicked", Toast.LENGTH_SHORT).show();        } else if (id == R.id.nav_manage) {            Toast.makeText(getApplicationContext(), "Tools is clicked", Toast.LENGTH_SHORT).show();        } else if (id == R.id.nav_share) {            Toast.makeText(getApplicationContext(), "Share is clicked", Toast.LENGTH_SHORT).show();        } else if (id == R.id.nav_send) {            Toast.makeText(getApplicationContext(), "Send is clicked", Toast.LENGTH_SHORT).show();        }        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);        drawer.closeDrawer(GravityCompat.END);        return true;    }}

Important inferences drawn from the above code are:

从以上代码得出的重要推论是:

  1. toggle.setDrawerIndicatorEnabled(false); : This line is used to hide the default hamburger icon that was displayed on the left.

    toggle.setDrawerIndicatorEnabled(false); :此行用于隐藏显示在左侧的默认汉堡包图标。
  2. All the GravityCompat constants are now changed to END instead of START.

    现在,所有GravityCompat常量都更改为END而不是START

The output of the application in action is given below.

实际应用程序的输出如下。

This brings an end to android NavigationView tutorial. You can download the final Android NavigationViewStyling Project from the link below.

这就结束了android NavigationView教程。 您可以从下面的链接下载最终的Android NavigationViewStyling项目

翻译自:

转载地址:http://nmlzd.baihongyu.com/

你可能感兴趣的文章
JAVA 基础 / 第八课:面向对象 / JAVA类的方法与实例方法
查看>>
Ecust OJ
查看>>
P3384 【模板】树链剖分
查看>>
Thrift源码分析(二)-- 协议和编解码
查看>>
考勤系统之计算工作小时数
查看>>
4.1 分解条件式
查看>>
Equivalent Strings
查看>>
flume handler
查看>>
收藏其他博客园主写的代码,学习加自用。先表示感谢!!!
查看>>
H5 表单标签
查看>>
su 与 su - 区别
查看>>
C语言编程-9_4 字符统计
查看>>
在webconfig中写好连接后,在程序中如何调用?
查看>>
限制用户不能删除SharePoint列表中的条目(项目)
查看>>
【Linux网络编程】使用GDB调试程序
查看>>
feign调用spring clound eureka 注册中心服务
查看>>
ZT:Linux上安装JDK,最准确
查看>>
LimeJS指南3
查看>>
关于C++ const成员的一些细节
查看>>
《代码大全》学习摘要(五)软件构建中的设计(下)
查看>>