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

Android使用CoordinatorLayout实现底部弹出菜单

程序员文章站 2023-10-30 15:48:34
本文实例为大家分享了使用coordinatorlayout实现底部弹出菜单的具体代码,供大家参考,具体内容如下 第一步:添加依赖: compile "com...

本文实例为大家分享了使用coordinatorlayout实现底部弹出菜单的具体代码,供大家参考,具体内容如下

第一步:添加依赖:

compile "com.android.support:design:${project.properties.get("support")}"


第二步:布局引用:

<android.support.design.widget.coordinatorlayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#04827c">

  <relativelayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    //页面布局
    </relativelayout>

  <include //引入菜单布局
    android:id="@+id/au_bottom_sheet"
    layout="@layout/view_audio_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    app:behavior_hideable="true"
    app:behavior_peekheight="0dp"
    app:layout_behavior="@string/bottom_sheet_behavior" />
</android.support.design.widget.coordinatorlayout>

第三步:使用:

//找到bottomsheetbehavior
bottomsheetbehavior behavior = bottomsheetbehavior.from(findviewbyid(r.id.au_bottom_sheet));

//设置弹出高度
 behavior.setpeekheight(windowheight / 2);
 //默认隐藏
 behavior.setstate(bottomsheetbehavior.state_hidden);
 //添加消失监听
 behavior.setbottomsheetcallback(bottomsheetcallback);

添加菜单消失监听:

 //状态监听,通过这个监听菜单是否消失
  private bottomsheetbehavior.bottomsheetcallback bottomsheetcallback = new bottomsheetbehavior.bottomsheetcallback() {
    @override
    public void onstatechanged(@nonnull view bottomsheet, int newstate) {
      if (newstate == bottomsheetbehavior.state_hidden) {
        if (!isbehaviorshowing(behavior)) {
          //菜单已经消失
        }
      }

    }

    @override
    public void onslide(@nonnull view bottomsheet, float slideoffset) {
    //滑动监听
    }
  };

判断是否可见:

 private boolean isbehaviorshowing(bottomsheetbehavior behavior) {
    return behavior.getstate() == bottomsheetbehavior.state_collapsed
        || behavior.getstate() == bottomsheetbehavior.state_expanded
        || behavior.getstate() == bottomsheetbehavior.state_settling;
  }

收回菜单:

behavior.setstate(bottomsheetbehavior.state_hidden);

弹出菜单:

 behavior.setstate(bottomsheetbehavior.state_collapsed);

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