The navigation drawer is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the user swipes a finger from the left edge of the screen or, while at the top level of the app, the user touches the app icon in the action bar.

//导航抽屉是一个显示在屏幕左边的应用的主要的用于导航的选项面板。它大多数时间是隐藏的,但是当用户从屏幕左边清扫或者点击了action bar上的应用图标时,导航抽屉将会出现

This lesson describes how to implement a navigation drawer using the DrawerLayout APIs available in the Support Library.

Navigation Drawer Design

Before you decide to use a navigation drawer in your app, you should understand the use cases and design principles defined in the Navigation Drawer design guide.

Create a Drawer Layout


To add a navigation drawer, declare your user interface with a DrawerLayout object as the root view of your layout. Inside the DrawerLayout, add one view that contains the main content for the screen (your primary layout when the drawer is hidden) and another view that contains the contents of the navigation drawer.

//想要添加drawerlayout,要在你的根布局上生命使用DrawerLayout对象,在DrawerLayout中添加一个主页面view和一个侧边栏view

For example, the following layout uses a DrawerLayout with two child views: a FrameLayout to contain the main content (populated by a Fragment at runtime), and a ListView for the navigation drawer.

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->
    <ListView android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout>

This layout demonstrates some important layout characteristics:

//这个布局说明了一些重要的布局特性:

  • The main content view (the FrameLayout above) must be the first child in the DrawerLayout because the XML order implies z-ordering and the drawer must be on top of the content. //主view必须是drawerlayout的第一个子view
  • The main content view is set to match the parent view's width and height, because it represents the entire UI when the navigation drawer is hidden. //主view 的宽高必须设置成match_parent的
  • The drawer view (the ListViewmust specify its horizontal gravity with the android:layout_gravity attribute. To support right-to-left (RTL) languages, specify the value with "start" instead of "left" (so the drawer appears on the right when the layout is RTL). //drawer view 必须指定 android:layout_gravity属性,为了支持RTL语言,指定属性值为start 而不是left,这样当布局是rtl时drawer就会出现在右侧
  • The drawer view specifies its width in dp units and the height matches the parent view. The drawer width should be no more than 320dp so the user can always see a portion of the main content.//drawer的宽必须不超过320dp,这样用户就总可以看得到主view

Initialize the Drawer List


In your activity, one of the first things to do is initialize the navigation drawer's list of items. How you do so depends on the content of your app, but a navigation drawer often consists of a ListView, so the list should be populated by an Adapter (such as ArrayAdapter or SimpleCursorAdapter).

For example, here's how you can initialize the navigation list with a string array:

public class MainActivity extends Activity {
    private String[] mPlanetTitles;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    ...     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);         mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);         // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());         ...
    }
}

This code also calls setOnItemClickListener() to receive click events in the navigation drawer's list. The next section shows how to implement this interface and change the content view when the user selects an item.

Handle Navigation Click Events


When the user selects an item in the drawer's list, the system calls onItemClick() on the OnItemClickListener given to setOnItemClickListener().

What you do in the onItemClick() method depends on how you've implemented your app structure. In the following example, selecting each item in the list inserts a different Fragment into the main content view (the FrameLayout element identified by the R.id.content_frame ID):

private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        selectItem(position);
    }
} /** Swaps fragments in the main content view */
private void selectItem(int position) {
    // Create a new fragment and specify the planet to show based on position
    Fragment fragment = new PlanetFragment();
    Bundle args = new Bundle();
    args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
    fragment.setArguments(args);     // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
                   .replace(R.id.content_frame, fragment)
                   .commit();     // Highlight the selected item, update the title, and close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(mPlanetTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
} @Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}

Listen for Open and Close Events


To listen for drawer open and close events, call setDrawerListener() on your DrawerLayout and pass it an implementation ofDrawerLayout.DrawerListener. This interface provides callbacks for drawer events such as onDrawerOpened() and onDrawerClosed().

However, rather than implementing the DrawerLayout.DrawerListener, if your activity includes the action bar, you can instead extend theActionBarDrawerToggle class. The ActionBarDrawerToggle implements DrawerLayout.DrawerListener so you can still override those callbacks, but it also facilitates the proper interaction behavior between the action bar icon and the navigation drawer (discussed further in the next section).

//为了监听侧边栏打开关闭,需要监听DrawerListener,如果你的activity包含action bar,你也可以使用ActionBarDrawerToggle类,这个类是DrawerListener的实现类

As discussed in the Navigation Drawer design guide, you should modify the contents of the action bar when the drawer is visible, such as to change the title and remove action items that are contextual to the main content. The following code shows how you can do so by overridingDrawerLayout.DrawerListener callback methods with an instance of the ActionBarDrawerToggle class:

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    ...     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...         mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {             /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }             /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };         // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }     /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }
}

The next section describes the ActionBarDrawerToggle constructor arguments and the other steps required to set it up to handle interaction with the action bar icon.

Open and Close with the App Icon


Users can open and close the navigation drawer with a swipe gesture from or towards the left edge of the screen, but if you're using the action bar, you should also allow users to open and close it by touching the app icon. And the app icon should also indicate the presence of the navigation drawer with a special icon. You can implement all this behavior by using the ActionBarDrawerToggle shown in the previous section.

//如果你使用actionbar 你应该也允许用户通过点击app icon 来打开和关闭侧边栏,你可以实现这个行为通过使用ActionBarDrawerToggle

To make ActionBarDrawerToggle work, create an instance of it with its constructor, which requires the following arguments:

  • The Activity hosting the drawer.
  • The DrawerLayout.
  • A drawable resource to use as the drawer indicator.

    The standard navigation drawer icon is available in the Download the Action Bar Icon Pack.

  • A String resource to describe the "open drawer" action (for accessibility).
  • A String resource to describe the "close drawer" action (for accessibility).

Then, whether or not you've created a subclass of ActionBarDrawerToggle as your drawer listener, you need to call upon your ActionBarDrawerTogglein a few places throughout your activity lifecycle:

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    ...     public void onCreate(Bundle savedInstanceState) {
        ...         mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */
                ) {             /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
            }             /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle(mDrawerTitle);
            }
        };         // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);         getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    }     @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }     @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }     @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
          return true;
        }
        // Handle your other action bar items...         return super.onOptionsItemSelected(item);
    }     ...
}

For a complete example of a navigation drawer, download the sample available at the top of the page.

Creating a Navigation Drawer 创建一个导航侧边栏的更多相关文章

  1. Android UI开发第三十二篇——Creating a Navigation Drawer

    Navigation Drawer是从屏幕的左侧滑出,显示应用导航的视图.官方是这样定义的: The navigation drawer is a panel that displays the ap ...

  2. Navigation Drawer(导航抽屉)

    目录(?)[-] 创建一个导航抽屉 创建抽屉布局 初始化抽屉列表 处理导航项选点击事件 监听导航抽屉打开和关闭事件 点击应用图标来打开和关闭导航抽屉 创建一个导航抽屉 导航抽屉是一个位于屏幕左侧边缘用 ...

  3. 【转】Navigation Drawer(导航抽屉)

    创建一个导航抽屉 创建抽屉布局 初始化抽屉列表 处理导航项选点击事件 监听导航抽屉打开和关闭事件 点击应用图标来打开和关闭导航抽屉   创建一个导航抽屉 导航抽屉是一个位于屏幕左侧边缘用来显示应用程序 ...

  4. 用CSS变形创建圆形导航

    http://www.w3cplus.com/css3/building-a-circular-navigation-with-css-transforms.html 本文由陈毅根据SARA SOUE ...

  5. iOS开发——UI进阶篇(八)pickerView简单使用,通过storyboard加载控制器,注册界面,通过xib创建控制器,控制器的view创建,导航控制器的基本使用

    一.pickerView简单使用 1.UIPickerViewDataSource 这两个方法必须实现 // 返回有多少列 - (NSInteger)numberOfComponentsInPicke ...

  6. Android UI开发第三十三篇——Navigation Drawer For Android API 7

    Creating a Navigation Drawer中使用的Navigation Drawer的android:minSdkVersion="14",现在Android API ...

  7. Android设计和开发系列第二篇:Navigation Drawer(Develop)

    Creating a Navigation Drawer THIS LESSON TEACHES YOU TO: Create a Drawer Layout Initialize the Drawe ...

  8. Android设计和开发系列第二篇:Navigation Drawer(Design)

    Navigation Drawer Creating a Navigation Drawer The navigation drawer is a panel that transitions in ...

  9. 【原创+译文】官方文档中声明的如何创建抽屉导航栏(Navigation Drawer)

    如需转载请注明出处:http://www.cnblogs.com/ghylzwsb/p/5831759.html 创建一个抽屉导航栏 抽屉式导航栏是显示在屏幕的左边缘,它是应用程序的主导航选项面板.它 ...

随机推荐

  1. JavaScript中document.cookie

    “某些 Web 站点在您的硬盘上用很小的文本文件存储了一些信息,这些文件就称为 Cookie.”—— MSIE 帮助.一般来说,Cookies 是 CGI 或类似,比 HTML 高级的文件.程序等创建 ...

  2. Android 常用网站

    Android Design : http://www.sunjw.us/adchs/index.html Android Developers : http://developer.android. ...

  3. eclipse问题解决(link方式安装插件失败)

    使用 link 方式,离线安装 eclipse 插件时,经常失败. 一.常见的失败情况 link方式配好后,eclipse 启动,没有弹出任何信息. 查看当前工作空间——.metadata——.log ...

  4. BZOJ 1020 安全的航线flight

    Description 在设计航线的时候,安全是一个很重要的问题.首先,最重要的是应采取一切措施确保飞行不会发生任何事故,但同时也需要做好最坏的打算,一旦事故发生,就要确保乘客有尽量高的生还几率.当飞 ...

  5. BZOJ 1023 仙人掌图

    Description 如果某个无向连通图的任意一条边至多只出现在一条简单回路(simple cycle)里,我们就称这张图为仙人图(cactus).所谓简单回路就是指在图上不重复经过任何一个顶点的回 ...

  6. [BZOJ 2350] [Poi2011] Party 【Special】

    题目链接: BZOJ - 2350 题目分析 因为存在一个 2/3 n 大小的团,所以不在这个团中的点最多 1/3 n 个. 牺牲一些团内的点,每次让一个团内的点与一个不在团内的点抵消删除,最多牺牲 ...

  7. CreateProcessWithLogonW(好像可以指定进程的上下文环境)

    Creates a new process and its primary thread. Then the new process runs the specified executable fil ...

  8. Arrays.sort的粗略讲解

    排序算法,基本的高级语言都有一些提供.C语言有qsort()函数,C++有sort()函数,java语言有Arrays类(不是Array).用这些排序时,都可以写自己的排序规则. Java API对A ...

  9. Vim默认保存文件路径的设置

    在_vimrc文件中添加: exec 'cd ' . fnameescape('F:\') F:\ 换成自己所需的路径,这样在vim中新建文件后直接用命令“ :w 文件名”就可以自动保存到已定义的路径 ...

  10. COJ 0047 20702最大乘积

    20702最大乘积 难度级别:B: 运行时间限制:1000ms: 运行空间限制:51200KB: 代码长度限制:2000000B 试题描述 输入n个元素组成的序列s,你需要找出一个乘积最大的连续子序列 ...