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

 

        Navigation Drawer是从屏幕的左侧滑出,显示应用导航的视图。官方是这样定义的:

 

    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.



 

如下图指示:

 

       Navigation Drawer不同于SlidingDrawer,它不存在可以拖动的handle;它也不同于SlidingMenu,Navigation Drawer滑出时主屏幕视图不一定。Navigation Drawer是覆盖在主视图上的。

       Navigation Drawer是Android团对在2013 google IO大会期间更新的Support库(V13)中新加入的重要的功能。实现现Navigation Drawer需要使用最新支持库(V13)的DrawerLayout。Navigation Drawer的设计指南请参考 

Navigation Drawer design guide

Create a Drawer Layout


       创建Navigation Drawer需要DrawerLayout 作为界面根控件。在DrawerLayout里面第一个View为当前界面主内容;第二个和第三个View为Navigation Drawer内容。如果当前界面只需要一个Navigation Drawer,则第三个View可以省略。

 


      下面的例子中DrawerLayout里面包含两个View,第一个FrameLayout中是当前界面主要内容显示区域;第二个ListView为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>

 

 

上面的代码中有如下几点需要注意:

 

    • 1、显示界面主要内容的View (上面的 FrameLayout ) 必须为DrawerLayout的第一个子View, 原因在于 XML 布局文件中的View顺序为Android系统中的 z-ordering顺序,而Navigation Drawer必须出现在内容之上。
    • 2、显示界面内容的View宽度和高度设置为和父View一样,原因在于当Navigation Drawer不可见的时候,界面内容代表整个界面UI。
    • 3、Navigation Drawer (上面的 ListView必须使用android:layout_gravity属性设置水平的 gravity值 .如果要支持 right-to-left (RTL,从右向左阅读)语言 用 "start" 代替 "left" (当在 RTL语言运行时候,菜单出现在右侧)。
    • 4、抽屉菜单的宽度为 dp 单位而高度和父View一样。抽屉菜单的宽度应该不超过320dp,这样用户可以在菜单打开的时候看到部分内容界面。

 

Initialize the Drawer List

 

 

       在您的Activity中需要先初始化Navigation Drawer内容,根据您的应用需要Navigation Drawer的内容可能不是ListView,可以使用其他View。

 

      在上面的示例中,我们需要给Navigation Drawer的ListView设置一个Adapter来提供数据。如下所示:

 

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());

        ...
    }
}


      上面的代码调用了 setOnItemClickListener() 函数来接受Navigation Drawer点击事件。下面会介绍如何通过点击Navigation Drawer显示主界面内容。

Handle Navigation Click Events

 

       当用户选择Navigation Drawer List中的条目时,系统会调用  OnItemClickListener的 onItemClick()函数

 

       根据您的应用需要,onItemClick函数的实现方式可能不同。下面的示例中,选择Navigation Drawer条目会在程序主界面中插入不同的 Fragment 。

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

 

 

        如果需要监听菜单打开关闭事件,则需要调用 DrawerLayout类的 setDrawerListener() 函数,参数为 DrawerLayout.DrawerListener接口的实现该接口提供了菜单打开关闭等事件的回调函数,例如 onDrawerOpened() 和onDrawerClosed().

 

    如果您的Activity使用了 action bar,则您可以使用Support库提供的 ActionBarDrawerToggle 类,该类实现了 DrawerLayout.DrawerListener接口,并且您还可以根据需要重写相关的函数。该类实现了菜单和Action bar相关的操作。

 

    根据在 Navigation Drawer 设计指南中的介绍,当菜单显示的时候您应该根据情况隐藏ActionBar上的功能菜单并且修改ActionBar的标题。下面的代码演示了如何重写 ActionBarDrawerToggle 类的相关函数来实现该功能。

 

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) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View 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);
    }
}

 

Open and Close with the App Icon

 

 

    用户可以从屏幕边缘滑动来打开Navigation Drawer,如果您使用了 action bar,应该让用户通过点击应用图标也可以打开抽屉菜单。并且应用图标也应该使用一个特殊的图标来指示抽屉菜单。您可以使用 ActionBarDrawerToggle 类来实现这些功能。

 

    使用 ActionBarDrawerToggle ,先通过其构造函数来创建该对象,构造函数需要如下参数:

    • 1)显示Navigation Drawer的 Activity 对象
    • 2) DrawerLayout 对象
    • 3)一个用来指示Navigation Drawer的 drawable资源
    • 4)一个用来描述打开Navigation Drawer的文本 (用于支持可访问性)。
    • 5)一个用来描述关闭Navigation Drawer的文本(用于支持可访问性).
  •  

    无论你是否继承 ActionBarDrawerToggle 来实现Navigation Drawer监听器,您都需要在Activity的生命周期函数中调用ActionBarDrawerToggle 的一些函数。

如下所示:

 

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) {
                getActionBar().setTitle(mTitle);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View 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);
    }

    ...
}

 

/**
* @author 张兴业
*  iOS入门群:83702688
*  android开发进阶群:241395671
*  我的新浪微博:@张兴业TBOW
*/

 

代码下载:demo

参考:

https://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html

http://developer.android.com/training/implementing-navigation/nav-drawer.html

http://developer.android.com/design/patterns/navigation-drawer.html

 

 
posted @ 2013-10-10 19:46  张兴业  阅读(1580)  评论(0编辑  收藏  举报