google 原生态 抽屉式侧滑菜单 Android DrawerLayout 布局的使用介绍

废话不多说,直接上效果图:

  

其实谷歌官方已经给出了一个 关于DrawerLayout 使用的例子,只是处于 国内不能访问谷歌官网,看不到详细文档说明,所以在此 简单记录下  侧滑 抽屉式菜单的使用说明


1.由于 DrawerLayout 需要 android.support.v4 包的支持,所以,你的libs 下面不要包含 这个包。

2.首先布局文件如下

<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/frame_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

    <!-- the navigetion view -->

    <ListView
        android:id="@+id/drawer_list"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#9999cc"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" >
    </ListView>

</android.support.v4.widget.DrawerLayout>

注意:1.布局中的ListView 就是就是侧滑菜单 布局容器,其中 android:layout_gravity 属性必须赋值。 目的是侧滑菜单的显示位置,官方推荐使用“start”-----左侧  "end"----右侧

 不推荐使用 “left”---左侧,“right”---右侧。

            2.FrameLayout 显示主内容部分。

其实到了这一步就已经实现了侧滑菜单效果了,可以运行试试,只是现在的侧滑菜单里面没有任何元素。

3.代码编写如下:

package com.example.drawlayout1;

import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity implements OnItemClickListener {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private String[] menuLists;
	private ArrayAdapter<String> adapter;
	private ActionBarDrawerToggle mDrawerToggle;
	private String titleString;
	private int iSelect = -1;
	private View heandrView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		/*get the application title*/
		titleString = (String) getTitle();
		
		heandrView = LayoutInflater.from(this).inflate(R.layout.home_menu_list_header, null);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.drawer_list);
		mDrawerList.addHeaderView(heandrView);
		menuLists = getResources().getStringArray(R.array.menu_content);

		
		
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, menuLists);
		mDrawerList.setAdapter(adapter);
		mDrawerList.setOnItemClickListener(this);

		/*set the shadow for drawer at start(left) or end(right)*/
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);

		/*show the home icon*/
		getActionBar().setDisplayHomeAsUpEnabled(true);
		/*make sure the home icon enable click*/
		getActionBar().setHomeButtonEnabled(true);

		/*set the application ActionBar title changes*/
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			@Override
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				getActionBar().setTitle(R.string.please);
			}

			@Override
			public void onDrawerClosed(View drawerView) {
				super.onDrawerClosed(drawerView);
				if (-1 == iSelect) {
					getActionBar().setTitle(titleString);
				} else {
					getActionBar().setTitle(menuLists[iSelect-1]);
				}
			}
		};
		/*set the DrawerLayout Listener*/
		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;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		/*make sure the home icon enable click and display the DrawerLayout*/
		if (mDrawerToggle.onOptionsItemSelected(item)){
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Fragment contentFragment = new ContentFragment();
		Bundle args = new Bundle();
		iSelect = arg2;
		if (0 == iSelect){
			iSelect = 1;
		}
		args.putString("text", menuLists[iSelect-1]);
		contentFragment.setArguments(args);

		FragmentManager fm = getFragmentManager();
		fm.beginTransaction().replace(R.id.frame_content, contentFragment)
				.commit();
		mDrawerLayout.closeDrawer(mDrawerList);
	}

	
	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */
	@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);
	}

}
代码里边有注解,就不一一解释了。

@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		/*make sure the home icon enable click and display the DrawerLayout*/
		if (mDrawerToggle.onOptionsItemSelected(item)){
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

这段代码的目的:点击ActionBar导航栏上的Home 按键弹出和关闭 DrawerLayout 侧滑菜单。


/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */
	@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);
	}

这段代码的目的:谷歌官方极力推荐重写两个方法,第一个方法 实现ActionBar 的Home键和 DrawerLayout 抽屉菜单关联,并且ActionBar的Home 有动画效果。

第二个方法 是在横屏的时候调用。保存状态。

mDrawerList.setOnItemClickListener(this);

这段代码是添加DrawerLayout 抽屉菜单 里面元素的点击事件,代码中实现点击不同元素,替换不同FragMent。


/*set the application ActionBar title changes*/
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			@Override
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				getActionBar().setTitle(R.string.please);
			}

			@Override
			public void onDrawerClosed(View drawerView) {
				super.onDrawerClosed(drawerView);
				if (-1 == iSelect) {
					getActionBar().setTitle(titleString);
				} else {
					getActionBar().setTitle(menuLists[iSelect-1]);
				}
			}
		};
		/*set the DrawerLayout Listener*/
		mDrawerLayout.setDrawerListener(mDrawerToggle);

这段代码是 添加侧滑 菜单 DrawerLayout 的打开关闭监听事件,在打开关闭方法中重写 自己需要实现的效果。


最后附上 整个工程源码:源码工程

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
DrawerLayout的封装,对于菜单是ListView的应用来说,这个库提供了更直接的使用方式,你不再需要去写menu的布局,如果你对DrawerLayout使用没有信心,这个库使用起来可能会让你觉得简单些。项目地址:https://github.com/Arasthel/GoogleNavigationDrawerMenu效果图:如何使用方法1. 直接用java代码创建   1. 首先你需要创建个内容页的布局文件<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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"                 android:paddingLeft="@dimen/activity_horizontal_margin"                 android:paddingRight="@dimen/activity_horizontal_margin"                 android:paddingTop="@dimen/activity_vertical_margin"                 android:paddingBottom="@dimen/activity_vertical_margin"                 tools:context="com.dexafree.googlenavigationdrawermenusample.MainActivity">         <TextView                 android:text="Hello world!"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content" /> </RelativeLayout>   2. 创建菜单实例  mDrawer = new GoogleNavigationDrawer(this);   mDrawer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));      3. 创建菜单项  mDrawer.setListViewSections(new String[]{"Section A", "Section B", "Section C"}, // Main sections         new String[]{"Settings01", "Settings02"}, // Secondary sections         new int[]{R.drawable.ic_launcher}, // Main sections icon ids         null);   4. 设置内容页LayoutInflater inflater = getLayoutInflater(); View contentView = inflater.inflate(R.layout.main_content, null); mDrawer.addView(contentView, 0);  5. 设置选择监听器mDrawer.setOnNavigationSectionSelected(new GoogleNavigationDrawer.OnNavigationSectionSelected() {     @Override     public void onSectionSelected(View v, int i, long l) {           Toast.makeText(getBaseContext(), "Selected section: " i, Toast.LENGTH_SHORT).show();      } });   6. 最后将菜单附加到页面上setContentView(mDrawer);  方法2. 在xml中创建菜单实例及内容页<org.arasthel.googlenavdrawermenu.views.GoogleNavigationDrawer xmlns:android="http://schemas.android.com/apk/res/android"xmlns:drawer="http://schemas.android.com/apk/res-auto"android:id="@ id/navigation_drawer_container"android:layout_width="match_parent"android:layout_height="match_parent"drawer:list_paddingTop="?android:actionBarSize"drawer:drawer_gravity="start"drawer:list_mainSectionsEntries="@array/navigation_main_sections"drawer:list_secondarySectionsEntries="@array/navigation_secondary_sections"drawer:list_mainSectionsDrawables="@array/drawable_ids"drawer:list_secondarySectionsDrawables="@array/drawable_ids">   <FrameLayout       android:id="@ id/content_layout"       android:layout_width="match_parent"       android:layout_height="match_parent"/> </org.arasthel.googlenavdrawermenu.views.GoogleNavigationDrawer>  接下来就按照方法1的步骤3、步骤5.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值