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