下載地址:https://github.com/asijack/AndroidDrawerDemo
直接上效果圖如下:

是不是還不錯的樣子。
先看看布局文件吧
<android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/app_description"/> </RelativeLayout> <ListView android:id="@+id/navdrawer" android:layout_width="@dimen/navdrawer_width" android:layout_height="match_parent" android:layout_gravity="start" android:background="@android:color/white" android:choiceMode="singleChoice" android:divider="@android:color/transparent" android:dividerHeight="0dp" android:drawSelectorOnTop="false"> </ListView> </android.support.v4.widget.DrawerLayout>
需要注意一下幾點:
1、主要內容的視圖(TextView)必須是DrawLayout的第一個子元素, 因為導航抽屜是在主要內容視圖的上面.
2、主要內容視圖設置為匹配父視圖的寬度和高度, 因為它代表了整個界面導航抽屜是隱藏的.
3、抽屜視圖(ListView)必須指定其水平重力與android:layout_gravity屬性。
支持從右到左(RTL)語言,指定值與 "start" 代替 "left"(所以抽屜里出現在布局的右側當布局是RTL時).
4、抽屜視圖指定其寬度用dp單位和高度匹配父視圖。抽屜里的寬度不能超過320 dp, 所以用戶總是可以看到主要內容視圖的一部分.
在來看看代碼,代碼算是比較容易看懂的。下面講一下需要注意的幾個地方
1、onOptionsItemSelected
//當一個可標記項目被選中時,系統將調用特定的項目選擇方法比如 :onOptionsItemSelected @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { if (mDrawerLayout.isDrawerOpen(mDrawerList)) { mDrawerLayout.closeDrawer(mDrawerList); } else { mDrawerLayout.openDrawer(mDrawerList); } } return super.onOptionsItemSelected(item); }
當抽屜被打開或者說被選中時會調用這個方法。
2、OnPostCreate
//如果Activity實例是第一次啟動,則不調用,以后的每次重新啟動都會調用 @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); }
這個方法用的用的還是比較少的。官方的解釋是:
"Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called).
"就是說,當Activity徹底運行起來后回調onPostCreate方法
通常我們所熟知的activity的生命周期如下:

其實詳細一點的生面周期如下
onCreate onStart onPost onCreate onResume onPostResume
跳轉下一個activity onPause onStop
跟多請看這篇文章 畢竟這里不是詳細講生命周期
還有跟多的Activity生命期狀態相關的回調函數還有這個onNewIntent也是比較少見的,詳細的看這篇文章吧
關於這個方法onPostCreate
可以用在獲取當前Activity窗口view的寬高是一個比較好的選擇
言歸正傳本demo需要注意的第三點
3、onConfigurationChanged
我們知道在改變屏幕方向、彈出軟件盤和隱藏軟鍵盤等類似操作時,如果沒有設置AndroidManifest.xml 程序是會再次執行onCreate方法的。在AndroidManifest.xml 里面設置了android:onConfigurationChanged屬性后就不會再次執行onCreate方法,而會執行onConfigurationChanged這個方法
而且首行必須是super.onConfigurationChanged(xx);
代碼下載地址:下載地址:https://github.com/asijack/AndroidDrawerDemo
用Eclipse可直接導入運行
android studio 也可以導入,可能gradle版本第一點需要改下配置文件。哪里不足望指教3q
