赞
踩
DrawerLayout是Android V4包中的一个布局控件,用来实现一个抽屉样式的布局。
DrawerLayout通过设置子视图的layout_gravity来决定子视图停靠在屏幕的哪个边缘外侧,等待用户将它拖进来或点击按钮拉开抽屉。
下面是一个简单的DrawerLayout的布局文件中的代码:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <android.support.v7.widget.Toolbar
- android:id="@+id/toolbar"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:background="@color/colorPrimary"
- android:minHeight="?attr/actionBarSize" />
-
- <android.support.v4.widget.DrawerLayout
- android:id="@+id/drawer"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
-
- <ImageView
- android:id="@+id/bg"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:contentDescription="@string/app_name"
- android:scaleType="centerCrop"
- android:src="@mipmap/bg4" />
-
- <!-- android:layout_gravity:设置抽屉布局所在的位置,start或left左侧,end或right右侧 -->
- <ListView
- android:id="@+id/drawer_list"
- android:layout_width="256.0dip"
- android:layout_height="match_parent"
- android:layout_gravity="start"
- android:background="@color/colorPrimary"
- android:choiceMode="singleChoice"
- android:divider="#00000000" />
- </android.support.v4.widget.DrawerLayout>
- </LinearLayout>

在代码中,我们为ListView设置了layout_gravity属性为start,表示我们将ListView添加到抽屉中,并隐藏在屏幕的左边。如果我们将手指按在屏幕左边缘向右拖拽,可以将抽屉拖出来。
我们可以通过DrawerLayout对象的openDrawer()和closeDrawer()方法来打开或关闭抽屉。
接下来我们来介绍一下DrawerLayout和Toolbar结合使用的方法。
先看一下运行效果:
- // 初始化Toolbar
- setSupportActionBar(toolbar);
- // 点击可以弹出抽屉的按钮
- ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawer,
- toolbar, R.string.drawer_open, R.string.drawer_close);
- drawerToggle.syncState();
- drawer.addDrawerListener(drawerToggle);
ListView数据适配、ListView中Item的点击事件不再赘述。
以上就是对DrawerLayout的基础用法的介绍,下面贴出码云上的源码,供大家参考。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。