DrawerLayout学习笔记

基本步骤:

1>在XML中将DrawerLayout作为根视图

2>根视图中放两个View,第一个是主视图,即DrawerLayout隐藏的时候的视图,第二是就DrawerLayout的视图,之前Google是用ListView,现在是用NavigationView,省掉了写adapter的步骤

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.arenas.drawerlayouttest.MainActivity">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></FrameLayout>

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

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

注意事项:

1.主视图宽度高度match_parent,也就是当抽屉隐藏的时候要让用户看到全部内容

2.必须显示指出抽屉视图的layout_gravity属性,start为从左至右划出,end相反。不推荐使用left和right

3.抽屉视图的宽度以dp为单位,不要超过320dp,(为了让用户总能看到一些主视图)

3>监听点击事件

ActionBarDrawerToggle:ActionBar跟DrawerLayout的纽带

toggle = new ActionBarDrawerToggle(this,drawerLayout,null,R.string.draw_open,R.string.draw_close){
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                //code it
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                //code it
            }
        };
        drawerLayout.setDrawerListener(toggle);
原文地址:https://www.cnblogs.com/i-love-kobe/p/5540178.html