Android DrawerLayout布局实现类似页面切换效果

前言

​ 最近使用DrawerLayout布局实现了一个类似页面切换的效果,使伸出的抽屉占满界面,并禁止了原有的手势滑动效果,采用按钮点击的方式实现抽屉的关闭打开。

Demo

1、修改布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer"
    tools:context=".MainActivity">

    <!-- 主显示页面 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/purple_200">
        <Button
            android:id="@+id/btn_open"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="open"
            />
    </RelativeLayout>
    
    <!-- 抽屉页面,必须包含layout_gravity属性 -->
    <RelativeLayout
        android:layout_width="match_parent"// 宽度设置为match_parent才能全屏显示
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:layout_marginRight="-65dp"	// 顶替掉默认抽屉的边缘区域
        android:background="#5382B1">

        <Button
            android:id="@+id/btn_close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Close" />

    </RelativeLayout>

</androidx.drawerlayout.widget.DrawerLayout>

这里只进行了一个DrawerLayout的简单使用

  • 抽屉部分必须设置layout_gravity属性,标识抽屉滑出方向
  • 设置属性layout_marginRight=“-65dp”,因为滑出抽屉后,最大剩余部分为65dp
  • 设置两个按钮,用于打开关闭抽屉

2、MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button btn_open;
    Button btn_close;
    DrawerLayout drawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_open = findViewById(R.id.btn_open);
        btn_close = findViewById(R.id.btn_close);
        drawerLayout = findViewById(R.id.drawer);
        
        // 关闭默认的手势滑动
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        
        // 按钮点击事件
        btn_open.setOnClickListener(v -> drawerLayout.openDrawer(Gravity.LEFT));
        btn_close.setOnClickListener(v -> drawerLayout.closeDrawer(Gravity.LEFT));

    }
}

如上代码所示,获取布局设置关闭手势滑动,设置按钮点击事件控制抽屉开合。

3、效果演示

在这里插入图片描述

4、参考

全屏显示: https://blog.csdn.net/wu88299/article/details/51595201

关闭手势滑动:https://blog.csdn.net/sm7890123/article/details/44179405

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值