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

设置focusable=false后,如何重新让EditText获取焦点并可编辑?

问题:EditText设置focusable="false"后无法重新获取焦点并编辑

我在XML布局里给EditText设置了focusable="false",点击按钮时想让它重新获取焦点并允许编辑,但设置focusable=true后还是不行——光标不显示,键盘也弹不出来。

XML布局代码:

<EditText
        android:id="@+id/et_display_name"
        android:layout_width="0dp"
        android:layout_height="44dp"
        android:layout_marginTop="40dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:background="@drawable/profile_shape"
        android:text="Display Name"
        android:textColor="@color/grey"
        android:inputType="textPersonName"
        android:cursorVisible="false"
        android:focusable="false"
        android:maxLines="1"
        android:maxLength="30"
        android:textSize="20sp"
        android:gravity="fill"
        android:paddingStart="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/iv_profilePic" />

我尝试了以下代码,但没有效果:

etDisplayName.focusable = View.FOCUSABLE
etDisplayName.requestFocus()
etDisplayName.isCursorVisible = true

解决方案

要让EditText从不可编辑状态切换为可编辑,需要同时配置焦点属性并手动触发软键盘,具体做法:

  • 同时设置isFocusable和isFocusableInTouchMode为true,确保EditText能通过触摸获取焦点
  • 调用requestFocus()主动请求焦点
  • 开启光标可见
  • 借助InputMethodManager手动弹出软键盘

完整Kotlin代码示例:

etDisplayName.apply {
    isFocusable = true
    isFocusableInTouchMode = true
    requestFocus()
    isCursorVisible = true
    // 弹出软键盘
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

关键说明

  • 仅设置focusable不足以让EditText在触摸时获取焦点,必须同时开启focusableInTouchMode
  • 系统不会自动弹出软键盘,需要通过InputMethodManager主动触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:05:09