ModalBottomSheetLayout
@Composable
@ExperimentalMaterialApi
fun ModalBottomSheetLayout(
sheetContent: @Composable ColumnScope.() -> Unit,
modifier: Modifier = Modifier,
sheetState: ModalBottomSheetState =
rememberModalBottomSheetState(ModalBottomSheetValue.Hidden),
sheetShape: Shape = MaterialTheme.shapes.large,
sheetElevation: Dp = ModalBottomSheetDefaults.Elevation,
sheetBackgroundColor: Color = MaterialTheme.colors.surface,
sheetContentColor: Color = contentColorFor(sheetBackgroundColor),
scrimColor: Color = ModalBottomSheetDefaults.scrimColor,
content: @Composable () -> Unit
)
ModalBottomSheetLayout
可以在 App 的底部弹出,并且能够将背景暗化。
ModalSheetLayout
总共有三种状态:
Hidden
HalfExpanded
Expanded
一个简单的 ModalBottomSheetLayout
的例子是这样的:
val state = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
val scope = rememberCoroutineScope()
ModalBottomSheetLayout(
sheetState = state,
sheetContent = {
Column{
ListItem(
text = { Text("选择分享到哪里吧~") }
)
ListItem(
text = { Text("github") },
icon = {
Surface(
shape = CircleShape,
color = Color(0xFF181717)
) {
Icon(
painterResource(R.drawable.github),
null,
tint = Color.White,
modifier = Modifier.padding(4.dp)
)
}
},
modifier = Modifier.clickable { }
)
ListItem(
text = { Text("微信") },
icon = {
Surface(
shape = CircleShape,
color = Color(0xFF07C160)
) {
Icon(
painterResource(R.drawable.wechat),
null,
tint = Color.White,
modifier = Modifier.padding(4.dp)
)
}
},
modifier = Modifier.clickable { }
)
}
}
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(
onClick = { scope.launch { state.show() } }
) {
Text("点我展开")
}
}
}
Tips
目前使用 ModalBottomSheetLayout
需要标明 @ExperimentalMaterialApi
2. 收回 ModalBottomSheet
一般情况下,ModalBottomSheet
无法自动处理按下返回键就收起,所以我们可以用 BackHandler
来处理
在 ModalBottomSheet
后添加代码:
BackHandler(
enabled = (state.currentValue == ModalBottomSheetValue.HalfExpanded
|| state.currentValue == ModalBottomSheetValue.Expanded),
onBack = {
scope.launch {
state.hide()
}
}
)
3. 设置动画时间
ModalSheetLayout
默认用 state.show()
或者 state.hidden()
来弹出和收回
我们可以通过这样的方式来自定义动画时间
state.animateTo(ModalBottomSheetValue.Hidden, tween(1000))
弹出同理