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

Android 键盘弹出时如何上滑页面,避免登录页文本及输入框被遮挡?

解决方案

1. 调整AndroidManifest配置

找到对应LoginActivity的声明节点,设置软键盘模式为adjustResize,保证布局会跟随键盘弹出挤压可用空间:

<activity
    android:name=".ui.auth.LoginActivity"
    android:windowSoftInputMode="adjustResize" />

2. 修改XML布局属性

你之前布局无效的核心原因是NestedScrollView设置了wrap_content高度,无法跟随布局挤压触发滚动,做以下修改:

  • 给NestedScrollView修改高度为match_parent,添加fillViewport="true"属性,同时添加底部边距预留出底部固定按钮的显示空间,避免滚动内容被按钮遮挡:
<androidx.core.widget.NestedScrollView
    android:id="@+id/login_scroll_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:isScrollContainer="true"
    android:fillViewport="true"
    android:layout_marginBottom="120dp">
  • 给你的邮箱输入框EditText添加id方便后续焦点监听:
<EditText
    android:id="@+id/et_email"
    android:layout_width="match_parent"
    ... 其余原有属性保持不变 />

3. 可选优化(保证标题默认可见)

如果需要键盘弹出时标题自动固定在可见区域顶部,在LoginActivity的onCreate方法中添加焦点监听,触发滚动到顶部:

val scrollView = findViewById<NestedScrollView>(R.id.login_scroll_view)
val etEmail = findViewById<EditText>(R.id.et_email)
etEmail.setOnFocusChangeListener { _, hasFocus ->
    if (hasFocus) {
        // 滚动到顶部,保证标题完全展示
        scrollView.smoothScrollTo(0, 0)
    }
}

如果使用Java,对应代码如下:

NestedScrollView scrollView = findViewById(R.id.login_scroll_view);
EditText etEmail = findViewById(R.id.et_email);
etEmail.setOnFocusChangeListener((v, hasFocus) -> {
    if (hasFocus) {
        scrollView.smoothScrollTo(0, 0);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:06:02