Jetpack Composeでモーダルボトムシートを表示する

Jetpack Composeでモーダルボトムシート(Modal Bottom Sheet)を表示する方法。

モーダルボトムシートを表示するには、ModalBottomSheetLayout()を使用します。

val sheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
ModalBottomSheetLayout(
    sheetState = sheetState,
    sheetContent = {
        // Sheet content
    }
) {
    // 
}

sheetStateはモーダルボトムシートの状態です。

rememberModalBottomSheetState()は以下のような引数を取ります。

fun rememberModalBottomSheetState(
    initialValue: ModalBottomSheetValue,
    animationSpec: AnimationSpec<Float> = SwipeableDefaults.AnimationSpec,
    confirmStateChange: (ModalBottomSheetValue) -> Boolean = { true }
): ModalBottomSheetState

sheetContentには、モーダルボトムシートの中に表示するコンテンツを設定します。

    ModalBottomSheetLayout(
        sheetState = sheetState,
        sheetContent = {
            Row(modifier = Modifier.height(300.dp)) {
                Text(text = "Sheet")
            }
        },
    ) {
    }

最後の引数は、画面に表示するコンテンツを設定します。

    ModalBottomSheetLayout(
        sheetState = sheetState,
        sheetContent = {
            Row(modifier = Modifier.height(300.dp)) {
                Text(text = "Sheet")
            }
        },
    ) {
        Button(onClick = { scope.launch { sheetState.show() } }) {
            Text(text = "Show Sheet")
        }
    }

全体のソースコードは次のようになります。

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    @ExperimentalMaterialApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }
}

@ExperimentalMaterialApi
@Composable
fun MainContent() {
    val sheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
    val scope = rememberCoroutineScope()
    ModalBottomSheetLayout(
        sheetState = sheetState,
        sheetContent = {
            Row(modifier = Modifier.height(300.dp)) {
                Text(text = "Sheet")
            }
        },
    ) {
        Button(onClick = { scope.launch { sheetState.show() } }) {
            Text(text = "Show Sheet")
        }
    }
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください