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

Activity启动时TextInputLayout自动获焦,如何实现仅触摸时聚焦?

解决TextInputEditText在Activity启动时自动获焦的问题

要实现仅触摸EditText时才让它获得焦点,你需要阻止Activity启动时的自动焦点分配,以下是几种可行方案:

方案一:让根布局抢占焦点

在Activity的根布局(比如你的ConstraintLayout)中添加以下属性,让根布局成为第一个可获取焦点的View,从而阻止EditText自动获焦:

android:focusable="true"
android:focusableInTouchMode="true"

示例修改后的根布局结构:

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <!-- 你的其他控件,包括TextInputLayout -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputMobile"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:errorEnabled="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvMessage">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/edtEmail"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:drawableStart="@drawable/ic_mobile"
            android:drawablePadding="@dimen/_3sdp"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:fontFamily="@font/montserrat_regular"
            android:hint="@string/str_mobile_number"
            android:inputType="number"
            android:maxLength="10"
            android:paddingVertical="@dimen/_9sdp"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/_10ssp" />
    </com.google.android.material.textfield.TextInputLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

方案二:代码层面清除焦点

在Activity的onCreate方法中,手动清除EditText的焦点,同时可以隐藏自动弹出的软键盘:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

    TextInputEditText edtEmail = findViewById(R.id.edtEmail);
    edtEmail.clearFocus();
    // 隐藏软键盘
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}

为什么你之前的设置无效?

android:focusableInTouchMode="true"的作用是允许View在触摸时获取焦点,而非阻止它在Activity启动时自动获焦。系统默认会给布局中第一个可获取焦点的View自动分配焦点,所以需要通过其他方式打断这个逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:55:17