欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android实现侧滑菜单DrawerLayout

程序员文章站 2022-11-23 10:23:20
本文实例为大家分享了android实现侧滑菜单的具体代码,供大家参考,具体内容如下点击左侧滑动效果如下代码实现过程:1.导入框架build.gradle中//materialdesignimpleme...

本文实例为大家分享了android实现侧滑菜单的具体代码,供大家参考,具体内容如下

点击左侧滑动

效果如下

Android实现侧滑菜单DrawerLayout

代码实现过程:

1.导入框架build.gradle中

//materialdesign
implementation 'com.google.android.material:material:1.0.0'

2.xml文件

主要的界面放在drawerlayout 中,需要强调的是侧滑菜单也就是下图显示的textview一定要设置layout_gravity属性,我是从左侧滑动的,所以设置为start

<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"
 android:fitssystemwindows="true"
 tools:context=".mainactivity">

 <androidx.constraintlayout.widget.constraintlayout
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <androidx.appcompat.widget.toolbar
   android:id="@+id/toolbar"
   android:layout_width="match_parent"
   android:layout_height="?attr/actionbarsize"
   android:background="@color/colorprimary"
   app:layout_constrainttop_totopof="parent"
   app:popuptheme="@style/themeoverlay.appcompat.light" />

 </androidx.constraintlayout.widget.constraintlayout>

 <textview
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_gravity="start"
  android:background="#ffffff"
  android:fitssystemwindows="true"
  android:text="i am a textview" />

</androidx.drawerlayout.widget.drawerlayout>

3.mainactivity

绑定xml文件中的toobar

protected void setuptoobar() {
  toolbar = findviewbyid(r.id.toolbar);
  setsupportactionbar(toolbar);
  if (null != getsupportactionbar()) {
   getsupportactionbar().setdisplayhomeasupenabled(true);
  }
 }

mainactivity 中将点击之后触发侧边滑动的图片ic_menu动态放到toolbr中

@override
 protected void setupviews() {
  setuptoobar();
  drawerlayout = findviewbyid(r.id.drawer);
  if (null != getsupportactionbar()) {
   getsupportactionbar().sethomeasupindicator(r.drawable.ic_menu);
  }
 }

android.r.id.home 触发左侧滑动

@override
 public boolean onoptionsitemselected(menuitem item) {
  switch (item.getitemid()) {
   case android.r.id.home:
    drawerlayout.opendrawer(gravitycompat.start);
    break;
   case r.id.item_search:
    toast.maketext(mainactivity.this, "搜索", toast.length_short).show();
  }
  return true;
 }

到这就结束了。

4.后话

可以在主内容区里面再放一个布局,里面放各个fragment,就可以实现每个页面都有侧滑菜单的效果。
侧滑菜单里面的布局可以新建一个xml文件,然后include,可以看起来舒服点吧。
其他的效果后面慢慢来吧。
github下载地址

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。