На первом шаге вы должны изменить root представление (в вашем макете) с:
<androidx.constraintlayout.widget.ConstraintLayout
на:
<androidx.coordinatorlayout.widget.CoordinatorLayout
, потому что BottomSheet
нужно CoordinatorLayout
для его поведения.
На следующем шаге вы должны изменить свой макет:
- переместите
app:layout_behavior
из root в CardView
- переместите
app:id
из root в CardView
На последнем шаге измените приведение макета с:
val llBottomSheet = findViewById<View>(R.id.bottom_sheet) as LinearLayout
на
val llBottomSheet = findViewById<CardView>(R.id.bottom_sheet)
В макете у вас есть CardView
, поэтому приведение as LinearLayout
неверно.
Полный рабочий пример:
Код:
private fun initComponent() {
// get the bottom sheet view
val llBottomSheet = findViewById<CardView>(R.id.bottom_sheet)
// init the bottom sheet behavior
val bottomSheetBehavior = BottomSheetBehavior.from(llBottomSheet)
// change the state of the bottom sheet
bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
// set callback for changes
bottomSheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {}
override fun onSlide(bottomSheet: View, slideOffset: Float) {}
})
}
Макет:
<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="@android:color/transparent"
android:orientation="vertical"
app:behavior_hideable="true"
app:behavior_peekHeight="250dp">
<androidx.cardview.widget.CardView
android:id="@+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
app:cardCornerRadius="1dp"
app:cardElevation="20dp"
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="Dandelion Chocolate"
android:textAppearance="@style/TextAppearance.AppCompat.Headline" />
</androidx.cardview.widget.CardView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>