引言
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>