當前位置:編程學習大全網 - 源碼下載 - Android 原生BottomSheet 介紹及坑

Android 原生BottomSheet 介紹及坑

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

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

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

實際使用過程中主要依靠BottomSheetBehavior來控制BottomSheet的展示及回調。

BottomSheetBehavior 具有五種狀態:

設置狀態:

bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);

回調:

強調:

BottomSheetBehavior將能幫妳實現 常駐bottom sheet( persistent bottom sheet) 的場景, 但這個版本還提供了BottomSheetDialog 和 BottomSheetDialogFragment 來實現 modal bottom sheets 的場景。只需要將AppCompatDialog 或者AppCompatDialogFragment分別替換成上述的兩個控件,妳就擁有了 bottom sheet 風格的對話框

然而我們實際我們需要BottomSheetDialog 是展開的,而BottomSheetDialog只展示壹部分

原因:BottomSheetDialog默認是STATE_COLLAPSED,所有BottomSheetDialog 依靠peekHight來設置高度,系統BottomSheetDialog 默認高度為256dp(查源碼得知),那按理來說我們的BottomSheetDialog 高度該是256dp,但是我們實際發現BottomSheetDialog高度也不等於256dp。我們研究下BottomSheetBehavior的中控制BottomSheetDialog高度源碼:

通過源碼我們可以得知BottomSheetBehavior通過改變child的偏移量而控制BottomSheetDialog的高度,默認狀態為STATE_COLLAPSED,child向下移動mMaxOffset高度,從而控制child顯示高度為mPeekHeight,這就需要child與parent 頂部對齊,child的getTop 為0;

然而我們再去查看Android的BottomSheetDialog 內中布局R.layout.design_bottom_sheet_dialog,發現我們自定義的的BottomSheetDialog 的contentView 是放置在FrameLayout 中的,然而FrameLayout出於某些原因為垂直居中的,而不是頂部對齊,從而導致BottomSheetDialog在256dp的基礎上向下偏移,只展示壹部分。

所以我們可以通過下面方法解決BottomSheetDialog 的顯示問題

解決方法如下:

當我們設置bottomSheetDialog每次點擊後不new,而是直接show的話,然而當我們會bottomSheetDialog 展開後,我們將BottomSheetDialog劃下隱藏後, 再點擊展示BottomSheetDialog後,會發現頁面只是變暗,BottomsheetDialog未展開,這是由於之前我們劃下收縮隱藏BottomSheetDialog後,bottomSheetDialogBehavior的狀態為隱藏,再次show之後,系統未恢復bottomSheetDialogBehavior的狀態,還是隱藏,所以再次點擊後頁面只是變暗。

  • 上一篇:BT其他總結
  • 下一篇:在線英文翻譯成中文(輕松快捷,準確無誤)
  • copyright 2024編程學習大全網