BottomSheetBehavior 的两个用处

1. BottomSheetBehavior 简介

An interaction behavior plugin for a child view of CoordinatorLayout
to make it work as a bottom sheet.
链接:https://developer.android.google.cn/reference/android/support/design/widget/BottomSheetBehavior?hl=en

划重点:一定要是CoordinatorLayout的子view,不要混淆成 ConstraintLayout。否则就会出现:BottomSheetBehavior is not a child of CoordinatorLayout 的错误
BottomSheetBehavior 可以和 CoordinatorLayout 的子View 一起,实现底部弹窗效果,手指拖动该面板,可以实现随手指上下滑动,如图:
在这里插入图片描述

2. 实现方法

2.1 gradle 中添加依赖:

  implementation 'com.android.support:design:25.3.0'

2.2 布局文件引入

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cl"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <android.support.v4.widget.NestedScrollView
        android:id="@+id/bottom_sheet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:behavior_hideable="true"
        app:behavior_peekHeight="50dp"
        app:layout_behavior="@string/bottom_sheet_behavior"        >
          <!-- NestedScrollView里设置你的底部表长什么样的,也可以根据实际情况使用别的布局-->
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

PS: app:layout_behavior="@string/bottom_sheet_behavior" 这句一定不能省略,用于和BottomSheetBehavior 建立联系。 且该字符串已在库中定义,直接这样引用即可。否则,会出现如此错误:
“The view is not associated with BottomSheetBehavior ”。

2.3 java 代码中

        // The View with the BottomSheetBehavior
        CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.cl);
        View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet);
        final BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
        
        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                //这里是bottomSheet 状态的改变回调
            }
 
            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                //这里是拖拽中的回调,根据slideOffset可以做一些动画
            }
        });

2.4 几点说明

peekHeight是当Bottom Sheets关闭的时候,底部下表我们能看到的高度。
hideable 是当我们拖拽下拉的时候,bottom sheet是否能全部隐藏。
如果你需要监听Bottom Sheets回调的状态,可以通过setBottomSheetCallback来实现,onSlide方法是拖拽中的回调,根据slideOffset可以做一些动画 onStateChanged方法可以监听到状态的改变。
BottomSheetBehavior.State 总共有5种,如下:

STATE_COLLAPSED: 关闭Bottom Sheets,显示peekHeight的高度,默认是0
STATE_DRAGGING: 用户拖拽Bottom Sheets时的状态
STATE_SETTLING: 当Bottom Sheets view摆放时的状态。
STATE_EXPANDED: 当Bottom Sheets 展开的状态
STATE_HIDDEN: 当Bottom Sheets 隐藏的状态

3. 扩展-BottomSheetDialog

参考链接:
Material Design系列,Behavior之BottomSheetBehavior与BottomSheetDialog
— 该博文介绍详细,可参考学习

使用BottomSheetBehavior实现美团拖拽效果 https://www.jianshu.com/p/04711494868e

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章