Android中的NavigationView

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 this 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 ListView/RecyclerView by implementing a custom Adapter.

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

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 navigation view template, NavigationView

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

了解NavigationView (Understanding the NavigationView)

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

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

<android.support.design.widget.NavigationView/>

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的布局。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

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

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.journaldev.navigationviewstyling.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

The content_main.xml layout is listed below:

下面列出了content_main.xml布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.journaldev.navigationviewstyling.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

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

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

nav_header_main.xml

nav_header_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />

</LinearLayout>

activity_main_drawer.xml

activity_main_drawer.xml

<menu xmlns:android="https://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_camera"
            android:icon="@drawable/ic_menu_camera"
            android:title="Import" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Slideshow" />
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/ic_menu_manage"
            android:title="Tools" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="Send" />
        </menu>
    </item>

</menu>

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 :

android navigation view

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- The toolbar -->
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/AppTheme.AppBarOverlay"
    android:background="?attr/colorPrimary" />

<android.support.v4.widget.DrawerLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="match_parent">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />


</android.support.v4.widget.DrawerLayout>

</LinearLayout>

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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.journaldev.navigationviewstyling.MainActivity">
    
    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:src="@android:drawable/ic_dialog_email"
        android:layout_alignParentBottom="true"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

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中删除以下行

<item name="android:statusBarColor">@android:color/transparent</item>

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布局定义为

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- The toolbar -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:fitsSystemWindows="true"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:fitsSystemWindows="true"
            android:theme="@style/AppTheme.AppBarOverlay" />

        <FrameLayout
            android:id="@+id/drawer_button"
            android:layout_width="50dp"
            android:layout_height="?attr/actionBarSize"
            android:fitsSystemWindows="true"
            android:layout_alignParentRight="true"
            android:clickable="true">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|center_vertical"
                android:src="@drawable/ic_action_not_black" />
        </FrameLayout>


    </RelativeLayout>

    <android.support.v4.widget.DrawerLayout
        xmlns:android="https://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:fitsSystemWindows="true"
        android:layout_height="match_parent"
        tools:openDrawer="end">

        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="end"
            android:fitsSystemWindows="true"
            app:itemTextColor="#1d3f4c"
            app:itemIconTint="#cd4312"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/activity_main_drawer" />


    </android.support.v4.widget.DrawerLayout>

</LinearLayout>

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/imageView"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:src="@drawable/profile" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Anupam Chugh"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="www.JournalDev.com" />

</LinearLayout>

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.

android navigation view example right to left output

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

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

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

翻译自: https://www.journaldev.com/12648/navigationview-android

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值