Google I/O 2013 Android 更新了Support库,新版本的Support库中新加入了几个比较重要的功能。
具体可参考以下链接
Android Navigation Drawer Design :http://developer.android.com/design/patterns/navigation-drawer.html
Android Navigation Drawer 教程: Android Navigation Drawer Designhttp://developer.android.com/training/implementing-navigation/nav-drawer.html
Demo 运行效果如下所示
未打开抽屉状态
创建Drawer Layout
在需要抽屉菜单的界面,用DrawerLayout 作为界面根控件。在DrawerLayout里面第一个View为当前界面主内容;第二个和第三个View为抽屉菜单内容。如果当前界面只需要一个抽屉菜单,则第三个View可以省略。
下面的例子中DrawerLayout里面包含两个View,第一个FrameLayout中是当前界面主要内容显示区域(使用Fragment填充);第二个ListView为抽屉菜单。
<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"> <!-- As the main content view, the view below consumes the entire space available using match_parent in both dimensions. --> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- android:layout_gravity="start" tells DrawerLayout to treat this as a sliding drawer on the left side for left-to-right languages and on the right side for right-to-left languages. The drawer is given a fixed width in dp and extends the full height of the container. A solid background is used for contrast with the content view. --> <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>
上面的代码中有如下几点需要注意:
初始化抽屉菜单
在您的Activity中需要先初始化抽屉菜单内容,根据您的应用需要抽屉菜单内容的方式可能不一样。但是抽屉菜单通常是一个ListView,所以可以通过Adapter来填充ListView。
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findView(); if (savedInstanceState == null) { selectItem(0); } } @SuppressLint("NewApi") private void findView() { mTitle = mDrawerTitle = getTitle(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); mNavMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // nav drawer icons from resources mNavMenuIconsTypeArray = getResources() .obtainTypedArray(R.array.nav_drawer_icons); mNavDrawerItems = new ArrayList<NavDrawerItem>(); // adding nav drawer items to array // Home mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[0], mNavMenuIconsTypeArray .getResourceId(0, -1))); // Find People mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[1], mNavMenuIconsTypeArray .getResourceId(1, -1))); // Photos mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[2], mNavMenuIconsTypeArray .getResourceId(2, -1))); // Communities, Will add a counter here mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[3], mNavMenuIconsTypeArray .getResourceId(3, -1), true, "22")); // Pages mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[4], mNavMenuIconsTypeArray .getResourceId(4, -1))); // What's hot, We will add a counter here mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[5], mNavMenuIconsTypeArray .getResourceId(5, -1), true, "50+")); // Recycle the typed array mNavMenuIconsTypeArray.recycle(); // setting the nav drawer list adapter mAdapter = new NavDrawerListAdapter(getApplicationContext(), mNavDrawerItems); mDrawerList.setAdapter(mAdapter); mDrawerList.setOnItemClickListener(this);
处理菜单点击事件
当用户选择菜单List中的条目时,系统会调用 OnItemClickListener的 onItemClick()函数。
根据您的应用需要onItemClick函数的实现方式可能不同。下面的示例中,选择菜单条目会在程序主界面中插入不同的 Fragment(ID 为 R.id.content_frame 的FrameLayout)。
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } /** * Diplaying fragment view for selected nav drawer list item * */ private void selectItem(int position) { // update the main content by replacing fragments Fragment fragment = null; switch (position) { case 0: fragment = new HomeFragment(); break; case 1: fragment = new FindPeopleFragment(); break; case 2: fragment = new PhotosFragment(); break; case 3: fragment = new CommunityFragment(); break; case 4: fragment = new PagesFragment(); break; case 5: fragment = new WhatsHotFragment(); break; default: break; } if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment).commit(); // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); mDrawerList.setSelection(position); setTitle(mNavMenuTitles[position]); mDrawerLayout.closeDrawer(mDrawerList); } else { // error in creating fragment Log.e("MainActivity", "Error in creating fragment"); } } @SuppressLint("NewApi") @Override public void setTitle(CharSequence title) { mTitle = title; getActionBar().setTitle(mTitle); }
监听菜单打开关闭事件
如果需要监听菜单打开关闭事件,则需要调用 DrawerLayout类的 setDrawerListener() 函数,参数为 DrawerLayout.DrawerListener接口的实现。该接口提供了菜单打开关闭等事件的回调函数,例如 onDrawerOpened() 和onDrawerClosed().
如果您的Activity使用了 action bar,则您可以使用Support库提供的 ActionBarDrawerToggle 类,该类实现了 DrawerLayout.DrawerListener接口,并且您还可以根据需要重写相关的函数。该类实现了菜单和Action bar相关的操作。
根据在 Navigation Drawer 设计指南中的介绍,当菜单显示的时候您应该根据情况隐藏ActionBar上的功能菜单并且修改ActionBar的标题。下面的代码演示了如何重写 ActionBarDrawerToggle 类的相关函数来实现该功能。
// ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); } @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; } /* 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_refresh).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); }
通过应用图打开或关闭抽屉
用户可以从屏幕边缘滑动来打开抽屉菜单,如果您使用了 action bar,应该让用户通过点击应用图标也可以打开抽屉菜单。并且应用图标也应该使用一个特殊的图标来指示抽屉菜单。您可以使用 ActionBarDrawerToggle 类来实现这些功能。
要使用 ActionBarDrawerToggle ,先通过其构造函数来创建该对象,构造函数需要如下参数:
// enable ActionBar app icon to behave as action to toggle nav drawer getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); } @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; } /* 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_refresh).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle action buttons switch(item.getItemId()) { case R.id.action_search: Toast.makeText(this, R.string.action_search, Toast.LENGTH_SHORT).show(); return true; case R.id.action_refresh: Toast.makeText(this, R.string.action_refresh, Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } @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); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); }
到这来就完啦,还有不懂的可以去参看官方Docs
http://developer.android.com/training/implementing-navigation/nav-drawer.html
Demo 下载地址:http://download.csdn.net/detail/fx_sky/6705135