您的位置:首页 > 移动开发 > Android开发

Android DrawerLayout+NavigationView布局实现左右两边侧滑菜单

2016-07-05 16:56 656 查看
最近在练习写一个APP《儒释道网络电台》,需要用到两边侧滑菜单。

在Android Studio中有一个模板可以创建左侧抽屉侧滑菜单,但我的项目中需要两侧各有一个抽屉侧滑菜单。上网摸索,找到以下几个解决方案

AndroidDrawerLayout+fragment布局实现左右侧滑 
使用SlidingMenu
但我看到Android Studio中有一个模板中使用的是NavigationView,难道使用NavigationView就不能两侧都有抽屉菜单吗?

参考《AndroidDrawerLayout+fragment布局实现左右侧滑 》中的做法,我添加了两个NavigationView,两个的属性android:layout_gravity一个设置成start,一个设置成end。代码如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />

<android.support.design.widget.NavigationView
android:id="@+id/right_nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_server_header_main"
app:menu="@menu/activity_server_drawer" />

</android.support.v4.widget.DrawerLayout>如上,还各自定义了headerLayout和menu属性。
在Toolbar中添加一个代码,并在按扭的点击事件中加入下边的代码

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_select_server) {
//显示右侧栏
if (mDrawer_layout.isDrawerOpen(GravityCompat.START)) {
mDrawer_layout.closeDrawer(GravityCompat.START);
}
mDrawer_layout.openDrawer(GravityCompat.END);
return true;
}

return super.onOptionsItemSelected(item);
}

主要就一句,打开右侧抽屉菜单
mDrawer_layout.openDrawer(GravityCompat.END);

打开左侧抽屉菜单的代码不用写,在上边的XML文件中写义了
tools:openDrawer="start"
用上面模板生成的代码已经可以自然的打开左侧抽屉菜单了。

左右抽屉侧滑菜单用起来效果确实不错,创建也非常简单。

希望本文对你有用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息