DrawerLayout 是实现了侧滑菜单效果的控件。
DawerLayout 分为侧边菜单和主内容区两部分:
使用的注意事项
要使用 DrawerLayout,可以在 layout xml 文件中将 DrawerLayout 设置为根视图。
一个简单的从左边滑出侧滑栏的例子。
侧滑栏滑出后,后面的视图会有个阴影。
layout 文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:openDrawer="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="我是主页" />
</RelativeLayout>
<RelativeLayout
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="我是侧滑栏" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
效果:
需要注意的是,DrawerLayout 要设置tools:openDrawer="start"
;而且侧滑栏layout要设置android:layout_gravity="start"
。
如果改成tools:openDrawer="end"
,侧滑栏 layout 要设置android:layout_gravity="end"
。侧滑栏可以从右边滑出。
现在侧边栏放的是RelativeLayout。 也可以放一个RecyclerView。
监听侧滑栏的滑动事件,使用ActionBarDrawerToggle
。侧滑栏滑出时,在onDrawerSlide
方法中计算出滑动的距离。 然后主视图设置水平相对偏移距离setTranslationX
即可。
可在activity的onCreate方法执行配置操作
DrawerLayout root = findViewById(R.id.root);
final View contentView = findViewById(R.id.content_field);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, root, android.R.string.yes, android.R.string.cancel) {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
float slideX = drawerView.getWidth() * slideOffset;
contentView.setTranslationX(slideX);
}
};
root.addDrawerListener(actionBarDrawerToggle);
使用 DrawerLayout 的setScrimColor
方法,改变阴影颜色。默认的阴影颜色是 DEFAULT_SCRIM_COLOR = 0x99000000
。
DrawerLayout root = findViewById(R.id.root);
root.setScrimColor(Color.TRANSPARENT);
root.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); // 解锁
root.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); // 不检测从左到右的滑动动作
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有