###### tags: `Android` `Kotlin` `View` # BottomSheet 底部列表是可以在畫面的底部彈出一個畫面,但這樣跟有動畫的fragment沒有區別阿? No,其實它還有其他重要的功能,例如依照不同狀態進行顯示、上下滑動等 而這個BottomSheet主要分成兩種:常駐型、模態型 - 常駐型:用於顯示主介面的額外訊息、它開啟時主介面還是可以操作的,且有各種滑動狀態 - 模態型:它開啟時會阻擋與主畫面的互動,僅有開啟與關閉兩種狀態 ## 常駐型 請直接參考本文最下方的引用文章,寫的很詳細,這裡不贅述 ## 模態型 用法跟傳統的dialog類似,它其實是一個BottomSheetDialogFragment,它的xml不需要定義 behavior 和 peekHeight,只要把想要的畫面layout即可,再來用程式控制,以下是使用步驟: ### 創建 BottomSheetFragment 類別 ```kotlin= class BottomSheetFragment : BottomSheetDialogFragment() { override fun onStart() { super.onStart() val dialog = dialog if (dialog != null) { //在dialog中可以取得一個內建的bottomSheet view,取得後就可以對bottomSheet做外觀修改 val bottomSheet = dialog.findViewById<View>(R.id.design_bottom_sheet) //取得螢幕高度的像素 val metric = DisplayMetrics() activity?.windowManager.defaultDisplay.getMetrics(metric) val height = metric.heightPixels * 0.6 //BottomSheetDialog 最大高度 bottomSheet.layoutParams.height = height //Behavior透過id為 design_bottom_sheet 的 View 來獲取,就可以調用 BottomSheetBehavior 的 peekHeight 設置 BottomSheetDialog 顯示時的高度 BottomSheetBehavior.from(bottomSheet).peekHeight = height } } } ``` ### 使用方式 在要啟用的地方,輸入以下程式碼,這樣才能開啟BottomSheet ```kotlin val fragment = BottomSheetFragment() fragment.show(this.supportFragmentManager, fragment.javaClass.simpleName) ``` > [使用與介紹](http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2017/0327/7729.html) > [設置高度](http://www.voidcn.com/article/p-vtgwgqnn-nq.html) > [禁止滑動](https://juejin.im/post/5b40ab0ef265da0f7a1cddfe)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up