Android 原生BottomSheet 介紹及坑

Android Support Library 23.2 推出之后,增加了幾個(gè)功能,例如支持Vector Drawables 和Animated Vector Drawables;增加AppCompat DayNight 主題;Design 庫(kù)中增加Bottom Sheets,RecyclerView 支持 auto-measurement,之前的wrap_content ,match_parent 都將可以發(fā)揮作用等等

公司的App 之前使用過第三方的[BottomSheet] (https://github.com/soarcn/BottomSheet ),現(xiàn)在Android 有自己的BottomSheet 那還不趕緊換成原生的。然而好事多磨,Android 原生BottomSheet 資料太少,深研下去發(fā)現(xiàn)BottomSheet 就是個(gè)大坑!

BottomSheet 的使用:

BottomSheet 使用需要CoordinatorLayout作為父布局,BottomSheet 的布局作為CoordinatorLayout 的子布局,并且BottomSheetBehavior(比如加上app:layout_behavior=”android.support.design.widget.BottomSheetBehavior”)

<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="android.com.bottomsheets.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <include layout="@layout/bottom_sheet_main" />

</android.support.design.widget.CoordinatorLayout>

實(shí)際使用過程中主要依靠BottomSheetBehavior來控制BottomSheet的展示及回調(diào)。
BottomSheetBehavior 具有五種狀態(tài):

  • STATE_COLLAPSED: 默認(rèn)的折疊狀態(tài), bottom sheets只在底部顯示一部分布局。顯示高度可以通過 app:behavior_peekHeight 設(shè)置(默認(rèn)是0)
  • STATE_DRAGGING : 過渡狀態(tài),此時(shí)用戶正在向上或者向下拖動(dòng)bottom sheet
  • STATE_SETTLING: 視圖從脫離手指自由滑動(dòng)到最終停下的這一小段時(shí)間
  • STATE_EXPANDED: bottom sheet 處于完全展開的狀態(tài):當(dāng)bottom sheet的高度低于CoordinatorLayout容器時(shí),整個(gè)bottom sheet都可見;或者CoordinatorLayout容器已經(jīng)被bottom sheet填滿。
  • STATE_HIDDEN : 默認(rèn)無此狀態(tài)(可通過app:behavior_hideable 啟用此狀態(tài)),啟用后用戶將能通過向下滑動(dòng)完全隱藏 bottom sheet

設(shè)置狀態(tài):
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
回調(diào):

// The View with the BottomSheetBehavio 
View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet);
BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(findViewById(R.id.bottomSheet));

bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
        @Override
  public void onStateChanged(@NonNull View bottomSheet, int newState) {
            if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                text1.setText("Collapse Me!");
  } else {
                text1.setText("Expand Me!");
  }
        }

        @Override
  public void onSlide(@NonNull View bottomSheet, float slideOffset) {

        }
    });
}

強(qiáng)調(diào):

  • BottomSheet 點(diǎn)擊展示的默認(rèn)是折疊狀態(tài),不是完全展開狀況,所有如果需要完全展開,請(qǐng)?jiān)O(shè)置展開狀況

BottomSheetDialog

BottomSheetBehavior將能幫你實(shí)現(xiàn) 常駐bottom sheet( persistent bottom sheet)的場(chǎng)景, 但這個(gè)版本還提供了BottomSheetDialog 和 BottomSheetDialogFragment 來實(shí)現(xiàn) modal bottom sheets的場(chǎng)景。只需要將AppCompatDialog 或者AppCompatDialogFragment分別替換成上述的兩個(gè)控件,你就擁有了 bottom sheet 風(fēng)格的對(duì)話框

坑1:

然而我們實(shí)際我們需要BottomSheetDialog 是展開的,而BottomSheetDialog只展示一部分
原因:BottomSheetDialog默認(rèn)是STATE_COLLAPSED,所有BottomSheetDialog 依靠peekHight來設(shè)置高度,系統(tǒng)BottomSheetDialog 默認(rèn)高度為256dp(查源碼得知),那按理來說我們的BottomSheetDialog 高度該是256dp,但是我們實(shí)際發(fā)現(xiàn)BottomSheetDialog高度也不等于256dp。我們研究下BottomSheetBehavior的中控制BottomSheetDialog高度源碼:

 @Override
    public boolean onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) {
        // First let the parent lay it out
        if (mState != STATE_DRAGGING && mState != STATE_SETTLING) {
            parent.onLayoutChild(child, layoutDirection);
        }
        // Offset the bottom sheet
        mParentHeight = parent.getHeight();
        mMinOffset = Math.max(0, mParentHeight - child.getHeight());
        mMaxOffset = mParentHeight - mPeekHeight;
        if (mState == STATE_EXPANDED) {
            ViewCompat.offsetTopAndBottom(child, mMinOffset);
        } else if (mHideable && mState == STATE_HIDDEN) {
            ViewCompat.offsetTopAndBottom(child, mParentHeight);
        } else if (mState == STATE_COLLAPSED) {
            ViewCompat.offsetTopAndBottom(child, mMaxOffset);
        }
        if (mViewDragHelper == null) {
            mViewDragHelper = ViewDragHelper.create(parent, mDragCallback);
        }
        mViewRef = new WeakReference<>(child);
        mNestedScrollingChildRef = new WeakReference<>(findScrollingChild(child));
        return true;
    }

通過源碼我們可以得知BottomSheetBehavior通過改變child的偏移量而控制BottomSheetDialog的高度,默認(rèn)狀態(tài)為STATE_COLLAPSED,child向下移動(dòng)mMaxOffset高度,從而控制child顯示高度為mPeekHeight,這就需要child與parent 頂部對(duì)齊,child的getTop 為0;
然而我們?cè)偃ゲ榭碅ndroid的BottomSheetDialog 內(nèi)中布局R.layout.design_bottom_sheet_dialog,發(fā)現(xiàn)我們自定義的的BottomSheetDialog 的contentView 是放置在FrameLayout 中的,然而FrameLayout出于某些原因?yàn)榇怪本又械模皇琼敳繉?duì)齊,從而導(dǎo)致BottomSheetDialog在256dp的基礎(chǔ)上向下偏移,只展示一部分。
所以我們可以通過下面方法解決BottomSheetDialog 的顯示問題

解決方法如下:

  1. 通過bottomSheetDialog中contentView得到parentView,通過parentView 得到BottomSheetBehavior
  2. 測(cè)量bottomSheetDialog布局中content的高度,設(shè)置peekHight
  3. 設(shè)置bottomSheetDialog 的contentView 對(duì)應(yīng)的父布局CoordinatorLayout的Grivity 為Gravity.TOP | Gravity.CENTER_HORIZONTAL;
 final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
        View contentView = View.inflate(this, R.layout.bottom_sheet_avatar, null);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.avatar_open_photo:
                        openCamera();
                        break;
                    case R.id.avatar_open_picture:
                        openPicture();
                        break;
                }
                if (bottomSheetDialog != null && bottomSheetDialog.isShowing()) {
                    bottomSheetDialog.dismiss();
                }
            }
        };

        contentView.findViewById(R.id.avatar_open_photo).setOnClickListener(clickListener);
        contentView.findViewById(R.id.avatar_open_picture).setOnClickListener(clickListener);
        contentView.findViewById(R.id.avatar_cancel).setOnClickListener(clickListener);

        bottomSheetDialog.setContentView(contentView);
        View parent = (View) contentView.getParent();
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        contentView.measure(0, 0);
        behavior.setPeekHeight(contentView.getMeasuredHeight());
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) parent.getLayoutParams();
        params.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
        parent.setLayoutParams(params);
        bottomSheetDialog.show();

坑2:

當(dāng)我們?cè)O(shè)置bottomSheetDialog每次點(diǎn)擊后不new,而是直接show的話,然而當(dāng)我們會(huì)bottomSheetDialog 展開后,我們將BottomSheetDialog劃下隱藏后, 再點(diǎn)擊展示BottomSheetDialog后,會(huì)發(fā)現(xiàn)頁(yè)面只是變暗,BottomsheetDialog未展開,這是由于之前我們劃下收縮隱藏BottomSheetDialog后,bottomSheetDialogBehavior的狀態(tài)為隱藏,再次show之后,系統(tǒng)未恢復(fù)bottomSheetDialogBehavior的狀態(tài),還是隱藏,所以再次點(diǎn)擊后頁(yè)面只是變暗。

 @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.showBottomSheetDialogButton:
                if (bottomSheetDialog != null) {
                    bottomSheetDialog.show();
                    Log.i("0000", "behavior_state:" + bottomSheetDialogBehavior.getState());
                    Log.i("0000", "STATE_HIDDEN :" + BottomSheetBehavior.STATE_HIDDEN);
                    return;
                }

                bottomSheetDialog = new BottomSheetDialog(this);
                bottomSheetDialog.show();
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容