Android点击EditText时View无法完全向上滚动问题怎么解决?
解决方案
1. 修正布局XML约束
问题核心是当前ScrollView与按钮的约束逻辑错误,导致adjustResize无法正确计算可用高度,修改如下:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" <!-- 新增这行,确保系统窗口插入量计算正确 --> android:fitsSystemWindows="true"> <ScrollView android:id="@+id/scrollView" android:fillViewport="true" android:layout_width="match_parent" <!-- 高度改为0dp,匹配上下约束的可用高度 --> android:layout_height="0dp" app:layout_constraintTop_toBottomOf="@+id/toolbar" <!-- 底部约束到按钮顶部,而非父布局底部 --> app:layout_constraintBottom_toTopOf="@+id/saveInstructionsButton" <!-- 删掉多余的vertical_bias属性 --> > <!-- 内部子布局保持不变 --> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="126dp"> <!-- 三个EditText的代码完全保留即可 --> ... </androidx.constraintlayout.widget.ConstraintLayout> </ScrollView> <android.widget.Button android:id="@+id/saveInstructionsButton" style="@style/buttonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginBottom="@dimen/padding_default" android:gravity="center" android:imeOptions="actionDone" android:text="@string/instructions_button_text" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
2. 保留Manifest配置
你当前设置的android:windowSoftInputMode="adjustResize"是正确的,无需修改。
3. 修正滚动逻辑,设置焦点监听
之前的滚动方法调用时机不对,需要等软键盘弹出、布局重绘完成后再执行滚动。在Activity中添加如下代码:
// 给所有EditText设置焦点监听 listOf(第一个EditText的id, instructionsEditText, notesEditText).forEach { et -> et.setOnFocusChangeListener { _, hasFocus -> if (hasFocus) { // 延迟200ms执行滚动,等待软键盘弹出完成 scrollView.postDelayed({ // 滚动到当前获取焦点的EditText位置 val location = IntArray(2) et.getLocationInWindow(location) // 100是顶部预留间距,可根据需求自行调整 scrollView.smoothScrollTo(0, location[1] - 100) }, 200) } } }
修改完成后按钮会自动紧贴软键盘顶部,点击任意EditText时ScrollView会自动滚动到输入框可见位置,符合预期效果。
内容的提问来源于stack exchange,提问作者Jim Clermonts
相关产品推荐
相关产品推荐

