NestedScrollView内EditText被软键盘遮挡 如何实现自动滚动显示
解决方案
1. 确认Activity软键盘配置
先检查AndroidManifest.xml中对应Activity的配置,确保添加了adjustResize属性,保证布局可被软键盘顶起:
<activity android:name=".你的目标Activity名" android:windowSoftInputMode="adjustResize" />
2. 键盘弹出时执行滚动逻辑
你已经实现了软键盘状态监听,在监听到键盘弹出的回调中,添加如下滚动代码即可:
Kotlin示例
// 用post等待布局测量完成,避免拿到错误的控件坐标 scrollView.post { // 计算需要滚动的目标Y值:bottom_layout顶部位置 + 自身高度 - NestedScrollView可视高度 val targetY = bottom_layout.top + bottom_layout.height - scrollView.height // 可自定义额外边距,避免控件贴住软键盘顶部 val extraMargin = (20 * resources.displayMetrics.density).toInt() if (targetY > 0) { scrollView.smoothScrollTo(0, targetY + extraMargin) } }
Java示例
scrollView.post(new Runnable() { @Override public void run() { int targetY = bottomLayout.getTop() + bottomLayout.getHeight() - scrollView.getHeight(); int extraMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics()); if (targetY > 0) { scrollView.smoothScrollTo(0, targetY + extraMargin); } } });
3. 可选优化:点击EditText直接触发滚动
如果需要点击EditText时就提前触发滚动,可给EditText添加焦点监听:
editText.setOnFocusChangeListener { _, hasFocus -> if (hasFocus) { // 复用上面的滚动逻辑即可 } }
注意事项
- 必须用
post提交滚动任务,控件位置计算需要等布局测量完成才能拿到正确值,直接在监听回调中取坐标大概率会得到错误结果 - 如果计算出的targetY为负数,说明
bottom_layout本来就在可视区域内,无需滚动 - 你当前布局中NestedScrollView的
fillViewport="true"属性保留即可,不会影响滚动逻辑,用于适配内容不足一屏的场景
内容的提问来源于stack exchange,提问作者Aziz Agasi
相关产品推荐
相关产品推荐

