如何使Google Material BottomSheetBehavior在搜索时完整显示于键盘上方?
解决BottomSheet点击搜索时完整显示于键盘上方的方案
1. 配置Activity软键盘适配模式
在AndroidManifest.xml对应Activity标签中添加以下属性,让布局随键盘弹出自动调整尺寸:
android:windowSoftInputMode="adjustResize|stateHidden"
2. 调整BottomSheetBehavior核心设置
确保BottomSheet绑定CoordinatorLayout后,强制设置展开状态并适配高度:
val bottomSheet = findViewById<View>(R.id.your_bottom_sheet_id) val behavior = BottomSheetBehavior.from(bottomSheet) // 强制BottomSheet展开至最大高度 behavior.state = BottomSheetBehavior.STATE_EXPANDED // 限制最大高度为屏幕高度,避免超出可视区域 behavior.maxHeight = resources.displayMetrics.heightPixels
3. 监听键盘弹出动态调整位置
通过布局全局监听判断键盘状态,实时修正BottomSheet偏移:
val rootView = findViewById<View>(android.R.id.content) rootView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { val visibleFrame = Rect() rootView.getWindowVisibleDisplayFrame(visibleFrame) val screenHeight = rootView.rootView.height val keyboardHeight = screenHeight - visibleFrame.bottom // 判定键盘弹出阈值(超过屏幕15%高度视为键盘弹出) if (keyboardHeight > screenHeight * 0.15) { val behavior = BottomSheetBehavior.from(bottomSheet) behavior.state = BottomSheetBehavior.STATE_EXPANDED // 将BottomSheet上移至键盘上方 bottomSheet.translationY = -keyboardHeight.toFloat() } else { bottomSheet.translationY = 0f } } })
4. 若使用BottomSheetDialogFragment的适配方案
如果BottomSheet基于DialogFragment实现,直接在Dialog配置中添加软键盘适配:
class SearchBottomSheet : BottomSheetDialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) return dialog } }
注意:BottomSheet的直接父布局必须是CoordinatorLayout,否则BottomSheetBehavior无法生效。
内容的提问来源于stack exchange,提问作者Ayaz Muhammad
相关产品推荐
相关产品推荐

