Android中實現BottomSheet的兩種方式

Android實現BottomSheet的方式有兩種,一種是Dialog的形式,一種是在當前佈局中進行添加,兩種都可以滿足不同的開發需求。先看效果圖:

                                

1.使用系統的BottomSheetDialog效果圖                       2.使用CoordinatorLayout的效果圖

首先,需要用到design庫,在build.gradle中添加依賴:

dependencies {
    ...
    implementation 'com.google.android.material:material:1.0.0'
}

方式一,先將佈局文件添加到BottomSheetDialog中:


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_bottom1)

    val view = View.inflate(this, R.layout.bottom_sheet_dialog1, null)

    ......

    val dialog = BottomSheetDialog(this)
    dialog.setContentView(view)
    val behavior = BottomSheetBehavior.from(view.parent as View)

}

打開BottomSheetDialog:

show_dialog.setOnClickListener {
            //顯示屏幕的一半
            behavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
            //也可以設置固定高度
            //behavior.peekHeight=600
            dialog.show()
}

BottomSheetDialog的父類是AppCompatDialog,所以我們也可以像普通的dialog一樣,通過BottomSheetDialog的構造方法設置style屬性。

接下來是方式二:

首先,創建activity的佈局activity_bottom2,父佈局是CoordinatorLayout

<androidx.coordinatorlayout.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">

  <Button
    android:id="@+id/show_dialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="30dp"
    android:text="顯示自定義的BottomSheetDialog"
    app:layout_constraintVertical_bias="0.3" />

  <DatePicker
    android:id="@+id/timePicker"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal"
    app:layout_behavior="@string/bottom_sheet_behavior"
    app:behavior_hideable="true"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

關鍵代碼是這一行:

app:layout_behavior="@string/bottom_sheet_behavior"

DatePicker的高度可以設置成match_parent,就可以滑動充滿全屏,如果設置成wrap_content則不能滑動到屏幕頂端,就只能顯示控件的高度。

然後拿到控件的Behavior就可以進行顯示、隱藏的操作了:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bottom2)

        val behavior = BottomSheetBehavior.from(timePicker)
        behavior.state = BottomSheetBehavior.STATE_HIDDEN
        show_dialog.setOnClickListener {
            if (behavior.state == BottomSheetBehavior.STATE_HIDDEN) {
                behavior.state = BottomSheetBehavior.STATE_COLLAPSED
            } else {
                behavior.state = BottomSheetBehavior.STATE_HIDDEN
            }
        }
}

代碼已經上傳到github上,覺得不錯的小夥伴給個star吧:https://github.com/HeJiaomy/BottomSheetDialog

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章