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

Android TextInputEditText动态设置Hint出现双提示问题如何解决

解决方案

问题根因

hint叠加是因为TextInputLayout会接管内嵌TextInputEditText的hint属性,同时自身也维护hint的显示逻辑,你单独修改EditText的hint不会同步到外层TextInputLayout,就会出现两个hint重叠的问题。

修复步骤

1. 修改布局文件

把原布局中写在TextInputEditText上的hint移动到外层TextInputLayout,并给TextInputLayout添加id:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/space_default">
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tilValue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="default"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/etValue"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </com.google.android.material.textfield.TextInputLayout>
</LinearLayout>

2. 修改业务代码

改为给外层TextInputLayout设置hint,无需再给EditText设置hint:

binding.clDireccion.setOnClickListener {
    val dialogView = layoutInflater.inflate(R.layout.dialog_configuration, null)
    val textInputLayout = dialogView.findViewById<TextInputLayout>(R.id.tilValue)
    val valueEditText = dialogView.findViewById<TextInputEditText>(R.id.etValue)
    
    // 直接修改TextInputLayout的hint即可完成替换
    textInputLayout.hint = "Direccion"
    
    MaterialAlertDialogBuilder(this)
        .setView(dialogView)
        .setCancelable(false)
        .setPositiveButton("Modificar") { dialogInterface, i ->
            val textValue = valueEditText.text.toString()
            with(preference.edit()) {
                putString(getString(R.string.sp_direccion), textValue).apply()
            }
        }
        .setNegativeButton("Cancelar", null)
        .show()
}

修改后可以完全保留EditText聚焦时hint自动上浮的原生交互效果,不会再出现hint重叠问题。


内容的提问来源于stack exchange,提问作者Isaac Caparrós González

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 10:42:03