You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让软键盘显示在多行TextInputEditText的选中行下方?

解决多行TextInputEditText软键盘跟随当前输入行的问题

你的场景是多行TextInputEditText默认软键盘显示在整个输入框底部,想要让软键盘紧贴当前光标所在的输入行下方,以下是可行的实现方案:

1. 调整布局配置

首先修改TextInputEditText的属性,确保输入框支持滚动且光标从顶部开始:

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/note"
    android:layout_marginTop="@dimen/layout_margin_default"
    app:startIconDrawable="@drawable/baseline_notes_24">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/noteEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:gravity="top"
        android:minLines="3"
        android:scrollbars="vertical" />

</com.google.android.material.textfield.TextInputLayout>
  • android:gravity="top":让输入内容从顶部开始,避免初始光标位于输入框中间导致软键盘位置偏移
  • android:minLines:设置输入框最小行数,保证初始有足够的输入区域
  • android:scrollbars="vertical":开启垂直滚动,支持输入内容超过可视区域时滚动

2. 配置窗口软键盘模式

在AndroidManifest.xml对应的Activity标签中设置windowSoftInputMode:

<activity
    android:name=".YourActivity"
    android:windowSoftInputMode="adjustResize|stateHidden">
    ...
</activity>
  • adjustResize:让系统调整窗口大小为软键盘腾出空间,输入框所在布局会自动向上移动
  • stateHidden:默认隐藏软键盘,点击输入框时再弹出

3. 监听光标位置,主动滚动到目标行

仅靠系统配置还不够,需要主动监听光标变化,让输入框滚动到当前光标所在行,确保软键盘紧贴该行下方:

val noteEditText = findViewById<TextInputEditText>(R.id.noteEditText)
noteEditText.setOnSelectionChangeListener { _, _ ->
    noteEditText.post {
        val layout = noteEditText.layout ?: return@post
        val cursorOffset = noteEditText.selectionStart
        val currentLine = layout.getLineForOffset(cursorOffset)
        val lineBottom = layout.getLineBottom(currentLine)
        
        // 计算滚动偏移,让当前行底部对齐输入框可视区域底部
        val targetScrollY = lineBottom - noteEditText.height + noteEditText.paddingBottom
        noteEditText.scrollTo(0, targetScrollY.coerceAtLeast(0))
    }
}
  • 通过post延迟执行,确保光标位置已完成更新
  • 计算当前光标所在行的底部位置,调整输入框滚动偏移,让该行始终处于输入框可视区域的底部,软键盘自然会紧贴该行下方

内容的提问来源于stack exchange,提问作者Funny Moments

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:01:23