
android 抽屉
In this tutorial you will learn about android navigation drawer.
在本教程中,您将了解android导航抽屉。
There are so little possibilities when it comes to choosing the main menu of an android application. If we start enlisting, we have TabLayout (used by the very famous WhatsApp), Bottom navigation drawer (used again by a facebook product Instagram) and then we have the most common form of menu ui and i.e. Navigation Drawer. Using a navigation drawer really adds a professional cover sort of thing to an android application and as an android developer, once you learn to implement it, trust me when I tell you this, it makes you feel as if you can now implement anything in an android application. I have been through that feeling and I wish you to experience the same. So, without any further delay, let’s get started on how to implement an Android Navigation Drawer.
选择android应用程序的主菜单时,可能性很小。 如果我们开始征募,我们将拥有TabLayout(由非常著名的WhatsApp使用),Bottom导航抽屉(由Facebook产品Instagram再次使用),然后我们将拥有最常见的ui菜单形式,即Navigation Drawer。 使用导航抽屉确实为android应用程序增加了专业的掩盖之物,作为android开发人员,一旦您学会实现它,请告诉我,请相信我,这让您感觉好像您现在可以在android应用程序。 我经历过这种感觉,希望您也能体验到。 因此,在没有任何延迟的情况下,让我们开始如何实现Android导航抽屉。
Android导航抽屉教程 (Android Navigation Drawer Tutorial)
创建一个新活动 (Creating a New Activity)
To begin with, hit the create a new project button in Android Studio and follow the steps below:-
首先,请在Android Studio中点击“创建新项目”按钮,然后执行以下步骤:-
Step 1: Assign a good name to your project.
步骤1:为您的项目分配一个好名字。

Step 2: Select the minimum android version that you want your app to support to.
第2步:选择您希望应用支持的最低Android版本。

Step 3: This is most important step in which you need to select the navigation drawer activity in order to implement the navigation drawer. So, go ahead and select the navigation drawer activity from list and hit next and then hit finish.
步骤3:这是最重要的步骤,您需要在其中选择导航抽屉活动以实现导航抽屉。 因此,继续并从列表中选择导航抽屉活动,然后单击下一步,然后单击完成。


Now let the project load and gradle be built and then we shall start configuring Navigation Drawer Activity.
现在,让项目装入和构建gradle,然后我们将开始配置Navigation Drawer Activity。
The project is all set by now to get started with code. Before doing so, let me give you a quick walk through of the file structure of this activity.
现在已设置好项目,以开始使用代码。 在开始之前,让我快速介绍一下此活动的文件结构。
在XML中 (In the XML)

In the first folder of res, we have directory by the name drawable and it simply contains all the xml icons for the drawer menu items.
在res的第一个文件夹中,我们有一个名为drawable的目录,它仅包含抽屉菜单项的所有xml图标。
In the next directory called layout, we have the all the layout files required for this activity. On the top of the list, we have the activity_main.xml which looks as shown below:-
在下一个名为layout的目录中,我们具有此活动所需的所有布局文件。 在列表的顶部,我们有activity_main.xml ,如下所示:-
activity_main.xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://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>
In the above xml code, we have an include envelope and then we have the NavigationView. This include envelope is being used here to render the code in the app_bar_main.xml layout file. The purpose of using include here is to maintain the cleanliness and readability of the code. The Parent layout for activity_main.xml is DrawerLayout.
在上面的xml代码中,我们有一个include信封,然后有NavigationView 。 这里使用了这个包含信封来在app_bar_main.xml布局文件中呈现代码。 在此使用include的目的是为了保持代码的整洁性和可读性。 activity_main.xml的父布局是DrawerLayout 。
The next layout file in the list is app_bar_main.xml and it looks something like below:-
列表中的下一个布局文件是app_bar_main.xml ,它看起来类似于以下内容:
app_bar_main.xml
app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dev.android.manish.navdrawertutorial.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"
app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
It simply has the Toolbar layout enclosed by the AppBarLayout which adds a shadow underneath the toolbar. Again here also we have a include envelope which refers to content_main.xml. So, content_main would be the place to display the different drawer screens. It also has a FloatinActionButton just as we have the YouTube App as the upload button. Well, it’s got nothing to do with navigation drawer activity so, we’ll just remove it once we start working on the navigation drawer.
它只是具有由AppBarLayout包围的工具栏布局,该布局在工具栏下方添加了阴影。 再次在这里,我们还有一个包含信封,它指向content_main.xml 。 因此,content_main将是显示不同抽屉屏幕的位置。 它也有一个FloatinActionButton ,就像我们将YouTube App作为上传按钮一样。 好吧,它与导航抽屉活动无关,因此,一旦我们开始在导航抽屉中工作,我们就将其删除。
The next layout file is content_main.xml and it looks as shown below:-
下一个布局文件是content_main.xml ,它看起来如下所示:-
content_main.xml
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="dev.android.manish.navdrawertutorial.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
The above code is where the content of the drawer screens is configured. Presently, it has nothing but a TextView saying Hello World but it’ll once we’re done configuring the Navigation Drawer.
上面的代码是配置抽屉屏幕内容的位置。 目前,它只不过是一个TextView,上面写着“ Hello World”,但一旦我们完成了导航抽屉的配置,它便会开始。
The next layout file is nav_header_main.xml and it occupies the header of the drawer layout as shown below:-
下一个布局文件是nav_header_main.xml ,它占据抽屉布局的标题,如下所示:-

Now you might wonder how has it been included in the main layout file i.e activity_main.xml. Well, it’s pretty simple. In the activity_main.xml, in the code for NavigationView, it has been included as the app:headerLayout to the drawer.
现在您可能想知道它如何包含在主布局文件(即activity_main.xml)中 。 好吧,这很简单。 在activity_main.xml中,在NavigationView的代码中,它已作为app:headerLayout包含在抽屉中。
The next directory is menu in the res folder and it has activity_main_drawer.xml which looks something like as shown below:-
下一个目录是res文件夹中的菜单 ,它具有activity_main_drawer.xml ,其外观如下图所示:
activity_main_drawer.xml
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://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>
- This file accounts for the all menu items which show up in the drawer, their titles, icons other behaviours. It has been set as menu to the NavgiationView in the activity_main.xml as app:menu. 此文件说明了出现在抽屉中的所有菜单项,其标题,其他行为的图标。 它已作为app:menu设置为activity_main.xml中NavgiationView的菜单。
That’s all for xml. Now we shall look into the java section and understand it’s flow.
这就是xml的全部内容。 现在,我们将研究Java部分并了解它的流程。
在Java中 (In the Java)
In the java part, we have just one class and i.e. MainActivity.java. It’s code looks as shown below:-
在Java部分中,我们只有一个类,即MainActivity.java 。 它的代码如下图所示:
MainActivity.java
MainActivity.java
package dev.android.manish.navdrawertutorial;
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);
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;
}
}
In the onCreate method of this class, we have Floatingactionbutton and the DrawerLayout initialized and configured. Also, we have the NavigationView initialized and the onItemClick listener has been set to display the screen as per the menu item selected.
在此类的onCreate方法中,我们已初始化并配置了Floatingactionbutton和DrawerLayout 。 另外,我们还对NavigationView进行了初始化,并且onItemClick侦听器已设置为根据所选菜单项显示屏幕。
The options menu has been rendered and their actions have been defined in the onCreateOptionMenu and onOptionsItemSelected methods respectively.
选项菜单已呈现,其动作已分别在onCreateOptionMenu和onOptionsItemSelected方法中定义。
Then, we have the OnNavigationItemSelected method where we’d handle the different menu item when clicked to render different screens as per the menu items.
然后,我们具有OnNavigationItemSelected方法,在该方法中,当单击以根据菜单项呈现不同的屏幕时,将处理不同的菜单项。
That’s all you needed to understand the flow of the code for the NavigationDrawerActivity.
这就是您了解NavigationDrawerActivity的代码流的全部所需。
Let’s start setting the NavigationDrawerActivity.
让我们开始设置NavigationDrawerActivity 。
Removing the FloatingActionButton:-
删除FloatingActionButton:-
Alright, we shall begin with removing the FloatingActionButton from the navigation drawer. To do so, remove the xml code for FloatingActionButton in the app_bar_main.xml. After removing it, the app_bar_main.xml would look something as shown below:-
好了,我们将从删除导航抽屉中的FloatingActionButton开始。 为此,请在app_bar_main.xml中删除FloatingActionButton的xml代码。 删除后,app_bar_main.xml看起来将如下所示:
app_bar_main.xml
app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dev.android.manish.navdrawertutorial.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.CoordinatorLayout>
Next in the MainActivity.java, we need to remove to code relating to FloatingActionButton. To do so, go ahead and delete the following lines from the onCreate method of MainActivity.java:-
接下来在MainActivity.java中 ,我们需要删除与FloatingActionButton有关的代码。 为此,请继续并从MainActivity.java的onCreate方法中删除以下几行:
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();
}
});
After deletion of the above lines, the MainActivity.java would look something as shown below:-
删除上述行后, MainActivity.java看起来将如下所示:
MainActivity.java
MainActivity.java
package dev.android.manish.navdrawertutorial;
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);
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);
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;
}
}
Now, Run the app and you shall find the FloatingActionButton gone.
现在,运行该应用程序,您将发现FloatingActionButton不见了。
配置抽屉菜单项 (Configuring Drawer Menu Items)
Now, we need to configure the menu items in the activity_main_drawer.xml file. To do so, open the aforementioned xml file and overwrite it with the code shown below:-
现在,我们需要在activity_main_drawer.xml文件中配置菜单项。 为此,请打开上述xml文件,并用以下代码覆盖它:-
activity_main_drawer.xml
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_one"
android:icon="@drawable/ic_menu_camera"
android:title="One" />
<item
android:id="@+id/nav_two"
android:icon="@drawable/ic_menu_gallery"
android:title="Two" />
<item
android:id="@+id/nav_three"
android:icon="@drawable/ic_menu_slideshow"
android:title="Three" />
</group>
</menu>
Each menu item has three basic attributes viz. id, title and icon. In the above code, we replaced the previous menu items with 3 menu items having titles One, Two and Three with item ids as nav_one, nav_two and nav_three respectively. The icons of these menu items have been left unchanged to avoid unnecessary imports. You can import the icons and change it later.
每个菜单项都有三个基本属性,即。 ID,标题和图标。 在上面的代码中,我们取代了以往的菜单项具有标题一 , 二和三分别物品ID作为nav_one,nav_two和nav_three 3个菜单项。 这些菜单项的图标保持不变,以避免不必要的导入。 您可以导入图标并在以后进行更改。
Now change the OnNavigationItemSelected method of the MainActivity.java class with the code as shown below:-
现在,使用如下所示的代码更改MainActivity.java类的OnNavigationItemSelected方法:
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_one) {
// Handle the camera action
} else if (id == R.id.nav_two) {
} else if (id == R.id.nav_three) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
In the above code, we just updated the ids of menu_items through which their actions were defined in this method. Like earlier you had, ids such as nav_camera, nav_gallery, etc here, but now we have ids such as nav_one, nav_two and nav_three and this is because we just updated the menu in the last step.
在上面的代码中,我们刚刚更新了menu_items的ID,通过该ID在此方法中定义了它们的动作。 像之前一样,这里有id,例如nav_camera , nav_gallery等,但是现在我们有了id,例如nav_one , nav_two和nav_three ,这是因为我们只是在最后一步更新了菜单。
- Now run the app and you shall find the drawer menu changed as shown below:- 现在运行该应用程序,您将发现抽屉菜单已更改,如下所示:-

设置屏幕内容 ( Setting Up the Screen Contents)
To set up the screen content, begin with changing the content_main.xml. Overwrite content_main.xml with the code shown below:-
要设置屏幕内容,请先更改content_main.xml。 用下面显示的代码覆盖content_main.xml :
content_main.xml
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dev.android.manish.navdrawertutorial.MainActivity"
android:id="@+id/container"
/>
- In the above code, we replaced the constraint layout with a FrameLayout which is used to block an area of the screen to display a certain content. You’ll realize later how it is being used exactly. So, keep moving. 在上面的代码中,我们用FrameLayout替换了约束布局,该FrameLayout用来阻塞屏幕的某个区域以显示特定内容。 稍后您将了解如何准确使用它。 因此,继续前进。
- We’re going to have three Fragments here in this project each having it’s class and a layout resource file. If you don’t have any idea of fragments, don’t worry. Consider fragments just as parts of an activity. i.e An activity can contain multiple fragments. 在这个项目中,我们将有三个片段,每个片段都有它的类和一个布局资源文件。 如果您不了解任何碎片,请不要担心。 将片段视为活动的一部分。 即一个活动可以包含多个片段。
Next, for the three fragments, create three java classes by the names of the drawer menu items viz One.class, Two.class and Three.class.
接下来,对于这三个片段,通过抽屉菜单项的名称vis One.class , Two.class和Three.class创建三个Java类。
- Next, make each of them extend them to Fragment v4. 接下来,使它们每个都扩展到Fragment v4。
Next, override the onCreateView method in each of these classes. This is the method where we’d specify the layout files for each of these fragments.
接下来,在每个这些类中重写onCreateView方法。 这是我们为每个片段指定布局文件的方法。
After the steps mentioned above, the One.java class would look something like shown below:-
完成上述步骤后, One.java类将如下所示:-
One.java
一个.java
package dev.android.manish.navdrawertutorial;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Manish on 9/27/2017.
*/
public class One extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Next, create three xml layout resource files by the names viz. fragment_one, fragment_two and fragment_three.
接下来,通过名称viz创建三个xml布局资源文件。 fragment_one , fragment_two和fragment_three 。
Each of these layout files would simply have a textView saying the name of the fragment.
这些布局文件中的每一个都将仅具有一个textView来说明片段的名称。
fragment_one.xml would look something like shown below:-
fragment_one.xml如下所示:-
fragment_one.xml
fragment_one.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="One"
android:textSize="25sp"
android:textColor="@android:color/black"
android:layout_centerInParent="true"
/>
</RelativeLayout>
Now, we have three Fragment classes namely One, Two and Three and we have three layout files for these fragment classes. To hook them up together, just update the onCreateView method in the three classes as shown below:-
现在,我们有三个片段类,分别是一个,两个和三个,并且对于这些片段类,我们有三个布局文件。 要将它们连接在一起,只需更新三个类中的onCreateView方法,如下所示:-
For One.java, do it as shown below:-
对于One.java ,如下所示:
One.java
一个.java
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
For Two.java, do it as shown below:-
对于Two.java ,如下所示:
Two.java
二.java
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
return view;
}
For Three.java, do it as shown below:-
对于Three.java ,如下所示:-
Three.java
三.java
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_three, container, false);
return view;
}
- Now, we have the three fragments all set. 现在,我们已经设置了三个片段。
将片段挂钩到抽屉菜单项 (Hooking the Fragments to the Drawer Menu Items)
To set the fragments up with the drawer menu items, we need to add a new method to the MainActivity.java and i.e. displaySelectedFragment(). The code for this method is given below. Just copy it and paste it in your MainActivity.java class.
要使用抽屉菜单项设置片段,我们需要向MainActivity.java中添加一个新方法,即displaySelectedFragment() 。 下面给出了此方法的代码。 只需将其复制并粘贴到您的MainActivity.java类中即可。
public void displaySelectedFragment(int item_id){
Fragment fragment = null;
switch (item_id){
case R.id.nav_one:
fragment = new One();
break;
case R.id.nav_two:
fragment = new Two();
break;
case R.id.nav_three:
fragment = new Three();
break;
}
if( fragment!=null ){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//this is where the id(R.id.container) of the FrameLayout in content_main.xml is being mentioned. Hence the fragment would be loaded into the framelayout
ft.replace(R.id.container, fragment);
ft.commit();
}
}
In the above method, according to the menu items of the drawer, different fragments are being loaded into the FrameLayout in the content_main.xml file.
在上述方法中,根据抽屉的菜单项,将不同的片段加载到content_main.xml文件的FrameLayout中。
Now, update the OnNavigationitemSelected method in the MainActivity.java class with the code given below:-
现在,使用下面给出的代码更新MainActivity.java类中的OnNavigationitemSelected方法:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// item id is being passed into the method here
displaySelectedFragment(item.getItemId());
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
In the above code, the displaySelectedFragment method which we just created has been called. We’re just passing the selected item_id in this method so as to display the fragment as per the item id.
在上面的代码中,我们刚刚创建的displaySelectedFragment方法已被调用。 我们只是在此方法中传递选定的item_id,以便根据项目ID显示片段。
- That’s it. You just linked all the fragments with drawer menu items successfully. 而已。 您刚刚将所有片段与抽屉菜单项成功链接。
- Run the app now and you shall find the fragment showing as per menu item selected as shown below:- 现在运行该应用程序,您将找到按所选菜单项显示的片段,如下所示:-



设置主屏幕 (Setting up Home Screen)
If you wish to have Fragment One as default fragment i.e. it appears as home screen, then just call the displaySelectedFragment() method at the end of onCreate method in MainActivity.java and pass the item id for the Fragment One i.e. R.id.nav_one just as shown below:-
如果希望将片段一作为默认片段,即它显示为主屏幕,则只需在MainActivity.java中onCreate方法结尾处调用displaySelectedFragment()方法,并传递片段一的项ID,即R.id.nav_one如下图所示:
-
设定画面标题 (Setting Screen Titles)
If you wish to change the toolbar title as per the selected drawer menu item, then first of all you need to make a reference global and that is navigationView.
如果您希望根据所选的抽屉菜单项更改工具栏标题,则首先需要创建一个全局引用,即navigationView 。
Mention the navigationView reference at the top of the MainActivity.java class as shown below:-
在MainActivity.java类的顶部提到navigationView参考,如下所示:-

Next, initialize it in the onCreate method as shown below:-
接下来,在onCreate方法中将其初始化,如下所示:-

Next, we need to add a method to the class MainActivity which would change the title of the screen as per the selected menu item. So, create a method by the name setScreenTitle() in MainActivity.java and copy the code given below into it’s body.
接下来,我们需要向MainActivity类添加一个方法,该方法将根据所选菜单项更改屏幕标题。 因此,在MainActivity.java中创建一个名为setScreenTitle()的方法,并将下面给出的代码复制到其主体中。
public void setScreenTitle(int item_id){
String title = "";
switch (item_id){
case R.id.nav_one:
title = "One";
break;
case R.id.nav_two:
title = "Two";
break;
case R.id.nav_three:
title = "Three";
break;
}
getSupportActionBar().setTitle(title);
}
Now, just call this method in the displaySelectedFragment method as shown below:-
现在,只需在displaySelectedFragment方法中调用此方法,如下所示:

- And you have done it. You have successfully learnt the implementation of Android Navigation Drawer. 您已经做到了。 您已经成功学习了Android导航抽屉的实现。
- Run the app now and you shall see your drawer running well as shown below. 立即运行该应用程序,您将看到抽屉运行正常,如下所示。



- To help you even further, we have the source code available here for this project. 为了进一步帮助您,我们在此处提供了此项目的源代码。
Comment below if you have any queries related to above android navigation drawer tutorial.
如果您对以上android导航抽屉教程有任何疑问,请在下面评论。
翻译自: https://www.thecrazyprogrammer.com/2017/10/android-navigation-drawer-tutorial.html
android 抽屉