BottomSheetの初期高さ(最初に表示されたときの高さ)を設定する方法を、ViewとComposeそれぞれで説明する。

View(BottomSheetBehavior)

BottomSheetBehaviorpeekHeight プロパティで初期高さを設定する。

XMLで設定する

レイアウトXMLで app:behavior_peekHeight 属性を指定する。

<FrameLayout
    android:id="@+id/bottom_sheet"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
    app:behavior_peekHeight="200dp">

    <!-- ボトムシートのコンテンツ -->

</FrameLayout>

コードで設定する

BottomSheetBehavior.from() でビューに紐づいた BottomSheetBehavior を取得し、peekHeight を設定する。単位はピクセルのため、dpをピクセルに変換して指定する。

Activityの場合は setContentView() の後であれば onCreate() で設定できる。

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val bottomSheet = findViewById<FrameLayout>(R.id.bottom_sheet)
        val behavior = BottomSheetBehavior.from(bottomSheet)

        val peekHeightPx = (200 * resources.displayMetrics.density).toInt()
        behavior.peekHeight = peekHeightPx
    }
}

Fragmentの場合は onViewCreated() で設定する。onCreateView() ではビューがまだ親の CoordinatorLayout にattachされていないことがあるため、onViewCreated() が適切である。

class ExampleFragment : Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val bottomSheet = view.findViewById<FrameLayout>(R.id.bottom_sheet)
        val behavior = BottomSheetBehavior.from(bottomSheet)

        val peekHeightPx = (200 * resources.displayMetrics.density).toInt()
        behavior.peekHeight = peekHeightPx
    }
}

peekHeightBottomSheetBehavior.PEEK_HEIGHT_AUTO を指定すると、16:9の比率に基づいて自動で高さを決定する。

Compose(BottomSheetScaffold)

Composeでは BottomSheetScaffoldsheetPeekHeight パラメータで初期高さを設定する。

BottomSheetScaffold(
    sheetContent = {
        // ボトムシートのコンテンツ
        Text("ボトムシートのコンテンツ")
    },
    sheetPeekHeight = 200.dp
) { innerPadding ->
    // メインコンテンツ
}

Compose(ModalBottomSheet)

ModalBottomSheetsheetState によって表示状態を制御する。初期状態を SheetValue.PartiallyExpanded に設定すると、peekHeight の高さで表示できる。

val sheetState = rememberModalBottomSheetState(
    initialValue = SheetValue.PartiallyExpanded,
    skipPartiallyExpanded = false
)

ModalBottomSheet(
    onDismissRequest = { /* 閉じる処理 */ },
    sheetState = sheetState
) {
    // ボトムシートのコンテンツ
    Text("ボトムシートのコンテンツ")
}

skipPartiallyExpandedfalse にして PartiallyExpanded の状態を有効にする。デフォルトは true(部分展開をスキップして全画面表示)のため指定が必要となる。

ModalBottomSheetBottomSheetScaffold と異なり sheetPeekHeight のようなパラメータは存在しない。部分展開時の高さはシートコンテンツの高さに依存する。高さを固定したい場合はコンテンツに Modifier.height() を指定する。

ModalBottomSheet(
    onDismissRequest = { /* 閉じる処理 */ },
    sheetState = sheetState
) {
    Box(modifier = Modifier.height(200.dp)) {
        // ボトムシートのコンテンツ
    }
}

参考