Android:如何让Bottom Sheet中键盘显示在EditText下方并覆盖RecyclerView?
实现方案
1. 配置Activity软输入模式
在AndroidManifest.xml里给对应Activity添加windowSoftInputMode属性,设置为adjustResize,让键盘弹出时窗口自动调整大小,Bottom Sheet会随之上移:
<activity android:name=".YourTargetActivity" android:windowSoftInputMode="adjustResize"> </activity>
2. 调整Bottom Sheet布局结构
让EditText布局在顶部,RecyclerView占满剩余空间,这样窗口resize时,RecyclerView会被挤到键盘区域实现覆盖效果。示例布局:
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- 顶部输入框 --> <EditText android:id="@+id/input_edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入内容"/> <!-- 下方列表 --> <androidx.recyclerview.widget.RecyclerView android:id="@+id/content_list" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> </LinearLayout>
3. 动态适配Bottom Sheet高度(可选)
如果默认resize效果达不到预期,可通过代码监听键盘状态,手动调整Bottom Sheet的高度和状态:
val bottomSheet = findViewById<View>(R.id.bottom_sheet_container) val behavior = BottomSheetBehavior.from(bottomSheet) // 监听窗口布局变化判断键盘状态 bottomSheet.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { val displayRect = Rect() window.decorView.getWindowVisibleDisplayFrame(displayRect) val screenHeight = window.decorView.rootView.height val keyboardHeight = screenHeight - displayRect.bottom if (keyboardHeight > screenHeight * 0.15) { // 键盘弹出,设置Bottom Sheet为展开状态,高度适配键盘上方区域 behavior.state = BottomSheetBehavior.STATE_EXPANDED behavior.maxHeight = displayRect.bottom } else { // 键盘收起,恢复默认高度 behavior.maxHeight = ViewGroup.LayoutParams.MATCH_PARENT } } })
4. 避免RecyclerView自动滚动(可选)
如果键盘弹出时RecyclerView自动滚动,可添加属性禁用该行为:
<androidx.recyclerview.widget.RecyclerView ... android:descendantFocusability="blocksDescendants"/>
内容的提问来源于stack exchange,提问作者Exception
相关产品推荐
相关产品推荐

