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