DrawerLayout的简单使用
引言
DrawerLayout,官方给我们提供的一个侧滑菜单控件,3.0以后引入,低版本使用它,需要v4兼容包,说到侧滑,相信很多人都用过github上的SlidingMenu,不过好像有两个版本,一个是单独的,另一个需要依赖另一 个开源项目:ActionBarSherlock;既然Google为我们提供了这个控件,为何不用咧,而且在Material Design设计规范中,随处可见的很多侧滑菜单的动画效果,大都可以通过Toolbar+DrawerLayout来实现~,下面来探究下这个DrawerLayout的一个基本用法~还有人喜欢把他称为抽屉控件~官方文档:DrawerLayout
使用的注意事项
1.主内容视图一定要是DrawerLayout的第一个子视图
2.主内容视图宽度和高度需要match_parent
3.代码中使用的时候,要调用openDrawer方法来打开
4.必须显示指定侧滑视图的android:layout_gravity属性
android:layout_gravity = “start”时,从左向右滑出菜单
android:layout_gravity = “end”时,从右向左滑出菜单
不推荐使用left和right!!!
侧滑视图的宽度以dp为单位,不建议超过320dp(为了总能看到一些主内容视图)
activity_main.xml:
1 <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:id="@+id/drawer_layout" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent"> 5 6 <!-- 主内容视图 --> 7 <FrameLayout 8 android:id="@+id/content" 9 android:layout_width="match_parent" 10 android:layout_height="match_parent" /> 11 12 <!-- 左侧滑菜单 --> 13 <include 14 android:id="@+id/main_menu_left" 15 layout="@layout/layout_main_menu" 16 android:layout_width="300dp" 17 android:layout_height="match_parent" 18 android:layout_gravity="start" /> 19 20 <!-- 右侧滑菜单 --> 21 <include 22 android:id="@+id/main_menu_right" 23 layout="@layout/layout_main_menu" 24 android:layout_width="100dp" 25 android:layout_height="match_parent" 26 android:layout_gravity="end" /> 27 28 </android.support.v4.widget.DrawerLayout>