1. 程式人生 > >使用CoordinatorLayout實現底部彈出選單

使用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);