Jetpack Compose中键盘显示在ModalBottomSheet后方而非上方的问题
Material3 ModalBottomSheet中OutlinedTextField键盘遮挡问题解决方案
在使用Material3库的ModalBottomSheet组件时,遇到异常行为:点击弹窗内的OutlinedTextField输入内容时,键盘会显示在弹窗后方,无法正常进行输入操作。
问题截图:
相关代码如下:
Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Row( Modifier.toggleable( value = skipHalfExpanded, role = Role.Checkbox, onValueChange = { checked -> skipHalfExpanded = checked } ) ) { Checkbox(checked = skipHalfExpanded, onCheckedChange = null) Spacer(Modifier.width(16.dp)) Text("Skip Half Expanded State") } Button(onClick = { openBottomSheet = !openBottomSheet }) { Text(text = "Show Bottom Sheet") } } // Sheet content if (openBottomSheet) { ModalBottomSheet( onDismissRequest = { openBottomSheet = false }, sheetState = bottomSheetState, ) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { Button( onClick = { scope.launch { bottomSheetState.hide() }.invokeOnCompletion { if (!bottomSheetState.isVisible) { openBottomSheet = false } } } ) { Text("Hide Bottom Sheet") } } InputTextField() } }
可行解决方案
方案1:添加IME padding
给ModalBottomSheet的内容布局外层添加Modifier.imePadding(),确保布局能随键盘弹出自动上移:
ModalBottomSheet( onDismissRequest = { openBottomSheet = false }, sheetState = bottomSheetState, ) { Column(Modifier.imePadding()) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { Button( onClick = { scope.launch { bottomSheetState.hide() }.invokeOnCompletion { if (!bottomSheetState.isVisible) { openBottomSheet = false } } } ) { Text("Hide Bottom Sheet") } } InputTextField() } }
方案2:配置Activity的软键盘模式
在AndroidManifest.xml中,给对应Activity添加windowSoftInputMode属性,设置为adjustResize:
<activity android:name=".YourActivity" android:windowSoftInputMode="adjustResize"> </activity>
方案3:监听键盘状态动态调整
使用rememberImeState监听键盘弹出状态,动态调整底部弹窗的布局 padding:
val imeState = rememberImeState() val bottomSheetState = rememberModalBottomSheetState( skipHalfExpanded = skipHalfExpanded, initialValue = ModalBottomSheetValue.Hidden ) ModalBottomSheet( onDismissRequest = { openBottomSheet = false }, sheetState = bottomSheetState, ) { Column( Modifier.padding(bottom = if (imeState.isVisible) 20.dp else 0.dp) ) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { Button( onClick = { scope.launch { bottomSheetState.hide() }.invokeOnCompletion { if (!bottomSheetState.isVisible) { openBottomSheet = false } } } ) { Text("Hide Bottom Sheet") } } InputTextField() } }
该问题已在Google官方问题追踪平台上报,后续可等待官方推出正式修复版本。
内容的提问来源于stack exchange,提问作者KSDev
相关产品推荐
相关产品推荐

