Android 抽屉组件DrawerLayout的简单使用

对于点击屏幕上按钮,从屏幕外上下左右划出一个菜单的场景,Android原生的DrawerLayout简单实用,这里记录一下

举例说明,效果如下

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/home_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.ReadKeyPointHomeActivity">

    <include
        android:id="@+id/content_layout"
        layout="@layout/layout_content" />

    <include
        android:id="@+id/menu_layout"
        layout="@layout/layout_menu"
        tools:visibility="gone" />
</androidx.drawerlayout.widget.DrawerLayout>

第一个content_layout是显示布局,第二个layout_menu是菜单布局

这里需要注意一下,可能会出现以下问题

1、菜单布局设置visible gone无效

2、菜单布局点击布局之外不可关闭

跟写法有关,注意看下menu_layout的布局代码

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_gravity="start"
    android:focusable="true"
    android:clickable="true"
    android:layout_width="250dp"
    android:layout_height="match_parent">

    <View
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:background="#0f0"
        app:layout_constraintLeft_toLeftOf="parent" />

    <Button
        android:id="@+id/btnMenuClose"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="200dp"
        android:layout_marginTop="100dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

可以看到

问题1是由于没有写android:layout_gravity="start"导致

问题2是由于没有写 android:focusable="true" android:clickable="true"导致

以上两点需要注意

然后是在Avtivity中的使用,非常的简单

    /**
     * 初始化抽屉组件
     */
    private fun initDrawerLayout() {
        // 禁止手势滑动
        mViewBinding.homeDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
        mViewBinding.homeContentLayout.btnUnitCheck.setOnClickListener {
            mViewBinding.homeDrawerLayout.openDrawer(GravityCompat.START, true)
        }
        mViewBinding.homeMenuLayout.btnMenuClose.setOnClickListener {
            closeDrawer()
        }
    }

    /**
     * 关闭抽屉组件
     */
    private fun closeDrawer() {
        mViewBinding.homeDrawerLayout.closeDrawer(GravityCompat.START, true)
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值