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

如何设置TextInputEditText只读可点击,点击弹出时间选择器并保留表单样式

实现方案

你不需要替换原有控件,只需要修改少量属性和添加代码逻辑即可满足需求,原有样式可以完全保留:

1. XML属性修改

给TextInputEditText添加以下属性,禁止输入相关交互:

<com.google.android.material.textfield.TextInputEditText
    android:id="@+id/edittext_add_name_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Name"
    <!-- 新增以下属性 -->
    android:cursorVisible="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:inputType="none" />

各属性作用:

  • cursorVisible="false":隐藏输入光标
  • focusable="false" + focusableInTouchMode="false":禁止控件获得输入焦点,不会弹出软键盘
  • inputType="none":禁用所有输入类型,避免输入法弹出

2. 代码逻辑配置

在Activity/Fragment中给控件设置点击事件,同时添加兜底的禁止输入逻辑:

Kotlin代码示例
val timeEdit = findViewById<TextInputEditText>(R.id.edittext_add_name_layout)
// 兜底禁止输入逻辑,避免属性配置遗漏导致的输入问题
timeEdit.keyListener = null
// 设置点击事件弹出时间选择器
timeEdit.setOnClickListener {
    // 示例使用系统TimePickerDialog,你也可以替换为自定义的时间选择器
    TimePickerDialog(this, { _, hour, minute ->
        // 将选择的时间格式化后设置到输入框
        timeEdit.setText(String.format("%02d:%02d", hour, minute))
    }, 0, 0, true).show()
}
Java代码示例
TextInputEditText timeEdit = findViewById(R.id.edittext_add_name_layout);
// 兜底禁止输入逻辑
timeEdit.setKeyListener(null);
// 点击事件
timeEdit.setOnClickListener(v -> {
    new TimePickerDialog(this, (view, hour, minute) -> {
        timeEdit.setText(String.format("%02d:%02d", hour, minute));
    }, 0, 0, true).show();
});

原理解释

你之前使用enabled=false不符合需求的原因是:该属性会将控件标记为完全禁用状态,不仅屏蔽输入能力,同时也会拦截所有触摸点击事件,还会自动将控件样式改为半透明的禁用态,破坏表单的视觉一致性。
本次方案的所有配置都只会屏蔽输入相关的交互,不会修改控件的默认视觉样式,也不会拦截点击事件,完全满足你的需求。

原样式参考

表单输入框样式示例


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:45:04