android 导航抽屉

In this tutorial we’ll implement a Navigation Drawer in our android application. Android navigation drawer is a sliding menu and it’s an important UI component. You will see navigation drawer in most of the android applications, it’s like navigation menu bars in the websites.

在本教程中,我们将在我们的android应用程序中实现一个导航抽屉 。 Android导航抽屉是一个滑动菜单,它是重要的UI组件。 您会在大多数android应用程序中看到导航抽屉,就像网站中的导航菜单栏一样。

Android导航抽屉 (Android Navigation Drawer)

Android Navigation Drawer is a sliding left menu that is used to display the important links in the application. Navigation drawer makes it easy to navigate to and fro between those links. It’s not visible by default and it needs to opened either by sliding from left or clicking its icon in the ActionBar.

Android导航抽屉是一个向左滑动菜单,用于显示应用程序中的重要链接。 导航抽屉可轻松在这些链接之间来回导航。 默认情况下它是不可见的,需要通过向左滑动或在ActionBar中单击其图标来打开它。

In broader terms, Navigation Drawer is an overlay panel, which is a replacement of an activity screen which was specifically dedicated to show all the options and links in the application.

从广义上讲,“导航抽屉”是一个覆盖面板,替代了专门用于显示应用程序中所有选项和链接的活动屏幕。

In this android navigation drawer tutorial we’ll implement the navigation drawer using the Drawer Layout API present in Android Support Library. We’ll show 3 fragment views that can be opened from the drawer items.

在此android导航抽屉教程中,我们将使用Android支持库中提供的Drawer Layout API来实现导航抽屉。 我们将显示3个可以从抽屉项目中打开的片段视图。

Android导航抽屉项目结构 (Android Navigation Drawer Project Structure)

Android导航抽屉示例 (Android Navigation Drawer Example)

To implement the Navigation Drawer we first need to add android.support.v4.widget.DrawerLayout as the root of the activity layout as shown below.

要实现导航抽屉,我们首先需要添加android.support.v4.widget.DrawerLayout作为活动布局的根,如下所示。

activity_main.xml

activity_main.xml

<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:layout_height="match_parent" ><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:id="@+id/container_toolbar"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><includeandroid:id="@+id/toolbar"layout="@layout/toolbar" /></LinearLayout><FrameLayoutandroid:id="@+id/content_frame"android:layout_width="match_parent"android:layout_height="match_parent" /></LinearLayout><ListViewandroid:id="@+id/left_drawer"android:layout_width="240dp"android:layout_height="match_parent"android:layout_gravity="start"android:background="#FFFFFF"android:choiceMode="singleChoice"android:divider="@android:color/darker_gray"android:dividerHeight="1dp" /></android.support.v4.widget.DrawerLayout>

The menu options in the navigation drawer are stored in the form of a ListView. Each option opens in the FrameLayout.

导航抽屉中的菜单选项以ListView的形式存储。 每个选项在FrameLayout中打开。

We’ve used a ToolBar in place of an ActionBar here. ToolBar has been introduced since Android 5.0 as a generalisation of ActionBar. It gives us more control and flexibility to modify and its easier to interleave with other views in the hierarchy.

我们在这里使用了ToolBar代替了ActionBar 。 从Android 5.0开始,ToolBar作为ActionBar的泛化引入。 它为我们提供了更多的控制权和修改的灵活性,并使其更易于与层次结构中的其他视图进行交错。

The layout ToolBar is defined in the xml layout given below.

布局工具栏在下面给出的xml布局中定义。

toolbar.xml

toolbar.xml

<android.support.v7.widget.Toolbar xmlns:android="https://schemas.android.com/apk/res/android"xmlns:local="https://schemas.android.com/apk/res-auto"android:id="@+id/toolbar"android:layout_width="match_parent"android:layout_height="wrap_content"android:minHeight="?attr/actionBarSize"android:background="?attr/colorPrimary"local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

We need to use the Theme Theme.AppCompat.NoActionBar in the styles.xml when using Toolbars.

使用工具栏时,我们需要在styles.xml中使用主题Theme.AppCompat.NoActionBar

The layout for the ListView rows in the Navigation Drawer is given below.

下面给出了导航抽屉中ListView行的布局。

list_view_item_row.xml

list_view_item_row.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="?android:attr/activatedBackgroundIndicator"android:minHeight="?android:attr/listPreferredItemHeightSmall"android:padding="10dp" ><ImageViewandroid:id="@+id/imageViewIcon"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentTop="true"android:paddingRight="10dp" /><TextViewandroid:id="@+id/textViewName"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_toRightOf="@+id/imageViewIcon"android:paddingRight="10dp"android:text="Item Name"android:textColor="@android:color/black"android:textAppearance="?android:attr/textAppearanceListItemSmall"/></RelativeLayout>

The navigation drawer items are put in a string array in the strings.xml file as shown below.

导航抽屉项目放置在strings.xml文件中的字符串数组中,如下所示。

strings.xml

strings.xml

<string-array name="navigation_drawer_items_array"><item>Connect</item><item>Fixtures</item><item>Table</item></string-array>

The DataModel.java class is used to define the objects for the drawer list items.

DataModel.java类用于定义抽屉式列表项的对象。

DataModel.java

DataModel.java

package com.journaldev.navigationdrawer;public class DataModel {public int icon;public String name;// Constructor.public DataModel(int icon, String name) {this.icon = icon;this.name = name;}
}

The drawer items are stored in the form of a ListView. Hence we need to use an Adapter Class to provide that data to the activity class.

抽屉项目以ListView的形式存储。 因此,我们需要使用适配器类将数据提供给活动类。

DrawerItemCustomAdapter.java

DrawerItemCustomAdapter.java

package com.journaldev.navigationdrawer;import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;public class DrawerItemCustomAdapter extends ArrayAdapter<DataModel> {Context mContext;int layoutResourceId;DataModel data[] = null;public DrawerItemCustomAdapter(Context mContext, int layoutResourceId, DataModel[] data) {super(mContext, layoutResourceId, data);this.layoutResourceId = layoutResourceId;this.mContext = mContext;this.data = data;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {View listItem = convertView;LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();listItem = inflater.inflate(layoutResourceId, parent, false);ImageView imageViewIcon = (ImageView) listItem.findViewById(R.id.imageViewIcon);TextView textViewName = (TextView) listItem.findViewById(R.id.textViewName);DataModel folder = data[position];imageViewIcon.setImageResource(folder.icon);textViewName.setText(folder.name);return listItem;}
}

The MainActivity.java source code is given below.

MainActivity.java源代码如下。

MainActivity.java

MainActivity.java

package com.journaldev.navigationdrawer;import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;public class MainActivity extends AppCompatActivity {private String[] mNavigationDrawerItemTitles;private DrawerLayout mDrawerLayout;private ListView mDrawerList;Toolbar toolbar;private CharSequence mDrawerTitle;private CharSequence mTitle;android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mTitle = mDrawerTitle = getTitle();mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);mDrawerList = (ListView) findViewById(R.id.left_drawer);setupToolbar();DataModel[] drawerItem = new DataModel[3];drawerItem[0] = new DataModel(R.drawable.connect, "Connect");drawerItem[1] = new DataModel(R.drawable.fixtures, "Fixtures");drawerItem[2] = new DataModel(R.drawable.table, "Table");getSupportActionBar().setDisplayHomeAsUpEnabled(false);getSupportActionBar().setHomeButtonEnabled(true);DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.list_view_item_row, drawerItem);mDrawerList.setAdapter(adapter);mDrawerList.setOnItemClickListener(new DrawerItemClickListener());mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);mDrawerLayout.setDrawerListener(mDrawerToggle);setupDrawerToggle();}private class DrawerItemClickListener implements ListView.OnItemClickListener {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {selectItem(position);}}private void selectItem(int position) {Fragment fragment = null;switch (position) {case 0:fragment = new ConnectFragment();break;case 1:fragment = new FixturesFragment();break;case 2:fragment = new TableFragment();break;default:break;}if (fragment != null) {FragmentManager fragmentManager = getSupportFragmentManager();fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();mDrawerList.setItemChecked(position, true);mDrawerList.setSelection(position);setTitle(mNavigationDrawerItemTitles[position]);mDrawerLayout.closeDrawer(mDrawerList);} else {Log.e("MainActivity", "Error in creating fragment");}}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {if (mDrawerToggle.onOptionsItemSelected(item)) {return true;}return super.onOptionsItemSelected(item);}@Overridepublic void setTitle(CharSequence title) {mTitle = title;getSupportActionBar().setTitle(mTitle);}@Overrideprotected void onPostCreate(Bundle savedInstanceState) {super.onPostCreate(savedInstanceState);mDrawerToggle.syncState();}void setupToolbar(){toolbar = (Toolbar) findViewById(R.id.toolbar);setSupportActionBar(toolbar);getSupportActionBar().setDisplayShowHomeEnabled(true);}void setupDrawerToggle(){mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.app_name, R.string.app_name);//This is necessary to change the icon of the Drawer Toggle upon state change.mDrawerToggle.syncState();}
}

In the above code getSupportActionBar().setDisplayHomeAsUpEnabled(false); is used to hide the default back button.

在上面的代码中, getSupportActionBar().setDisplayHomeAsUpEnabled(false); 用于隐藏默认的后退按钮。

In this code we’ve used a DrawerItemClickListener Class that loads the respective fragment of the list item clicked using a FragmentManager. Also the the title of the ToolBar is changed to the list item clicked using setTitle(mNavigationDrawerItemTitles[position]);.

在此代码中,我们使用了DrawerItemClickListener类, DrawerItemClickListener加载使用FragmentManager单击的列表项的相应片段。 同样,将工具栏的标题更改为使用setTitle(mNavigationDrawerItemTitles[position]);单击的列表项setTitle(mNavigationDrawerItemTitles[position]);

The fragment classes and their respective layouts are given below.

片段类及其各自的布局如下。

ConnectFragment.java

ConnectFragment.java

package com.journaldev.navigationdrawer;import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;public class ConnectFragment extends Fragment {public ConnectFragment() {}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View rootView = inflater.inflate(R.layout.fragment_connect, container, false);return rootView;}}

The layout of the above fragment is defined below.

以上片段的布局定义如下。

fragment_connect.xml

fragment_connect.xml

<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"android:orientation="vertical"><TextViewandroid:id="@+id/label"android:layout_alignParentTop="true"android:layout_marginTop="100dp"android:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="center_horizontal"android:textSize="45dp"android:text="Connect"android:textStyle="bold"/><TextViewandroid:layout_below="@id/label"android:layout_centerInParent="true"android:layout_width="fill_parent"android:layout_height="wrap_content"android:textSize="12dp"android:layout_marginTop="10dp"android:gravity="center_horizontal"android:text="Edit fragment_connect.xml to change the appearance"android:id="@+id/textView2" /></RelativeLayout>

The other two items are defined in exactly the same way as above hence we’re skipping it here.

其他两个项目的定义与上面完全相同,因此我们在这里跳过。

导航抽屉Android示例输出 (Navigation Drawer Android Example Output)

Below is the output produced by our navigation drawer android example application.

以下是我们的导航抽屉android示例应用程序产生的输出。

This brings an end to android navigation drawer example tutorial. You can download the final Android Navigation Drawer Project from the below link.

这结束了android导航抽屉示例教程。 您可以从下面的链接下载最终的Android导航抽屉项目

Download Android Navigation Drawer Example Project下载Android导航抽屉示例项目

翻译自: https://www.journaldev.com/9958/android-navigation-drawer-example-tutorial

android 导航抽屉

android 导航抽屉_Android导航抽屉示例教程相关推荐

  1. android浮动按钮_Android浮动操作按钮示例教程

    android浮动按钮 Today we will learn about Android Floating Action Button. We'll discuss the FloatingActi ...

  2. android圆角视图_Android图库视图示例教程

    android圆角视图 Android Gallery is a View commonly used to display items in a horizontally scrolling lis ...

  3. android实例教程_Android内部存储示例教程

    android实例教程 Today we will look into android internal storage. Android offers a few structured ways t ...

  4. 免费下载谷歌maps软件_Android Google Maps示例教程

    免费下载谷歌maps软件 In this tutorial we'll discuss and implement some interesting features of android googl ...

  5. Android开发之Navigationdrawer导航抽屉功能的实现(源代码分享)

    导航抽屉(navigationdrawer)是一个从屏幕左边滑入的面板,用于显示应用的主要导航项目.用户可以通过在屏幕左边缘滑入或者触摸操作栏的应用图标打开导航抽屉.导航抽屉覆盖在内容之上,但不覆盖操 ...

  6. jsf 导航_JSF页面导航示例教程

    jsf 导航 Page navigation is the redirection of a page based on the events performed for instance – on ...

  7. jsf 导航_JSF导航规则示例教程

    jsf 导航 JSF Navigation rules specifies the navigation between the pages on click of button or hyperli ...

  8. Android ActionBar示例教程

    Today we will look into Android ActionBar. Action Bar is one of the important part of any applicatio ...

  9. Android WebView示例教程

    Android WebView is used to display HTML in an android app. We can use android WebView to load HTML p ...

最新文章

  1. Bioinformatics:吉林大学刘富组-深度学习从宏基因组序列中识别短病毒序列Virtifier...
  2. 好好说一说室内定位技术
  3. 求两个datetime之间相差的天数
  4. 【翻译】如何创建Ext JS暗黑主题之一
  5. OpenTLD相关资料
  6. 你吃的瓜子仁,真是老奶奶磕出来的?!
  7. 使用JacpFX和JavaFX2构建富客户端
  8. servlet中访问mysql无法包含中文的解决
  9. 每日一题(43)—— 数组越界
  10. javascript进阶——Ajax
  11. 出现在嵌入式DSP上可用于实现各种编解码器
  12. 简单解决某盘限速?(黑科技)【油猴】+【某盘直链下载器】+【IDM下载】
  13. (亲测有效)windows10和11如何卸载Microsoft Edge浏览器
  14. 重构改善即有代码的设计
  15. 零基础自学画画的方法有哪些
  16. Win7电脑无法进入睡眠模式?
  17. win10+CUDA10.1+cudnn7.6+MX250安装过程
  18. 通行时间可调的两路口交通灯设计实验(基于Multisim仿真)
  19. Android 实战项目:简单计算器
  20. javascript事件触发器

热门文章

  1. Xorg可以使用hot-plug了,不过配置很麻烦
  2. [转载] python 运算符重载有什么用_Python运算符重载用法实例分析
  3. [转载] python字符串表示方法_python字符串使用方法归纳
  4. [转载] python numpy np.finfo()函数 eps
  5. [转载] Python利用pandas处理Excel数据的应用
  6. [转载] python 闭包和装饰器详解
  7. Django的Ajax加额外操作
  8. 用layui实现下拉框select多选,取值
  9. Java的JDK以及maven环境变量配置
  10. Ansible(自动化运维工具--playbook)