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

Android Material TextInputLayout的hint提示文本无法翻译如何解决

问题场景

开发多语言Android应用时,界面基于Material Design组件实现,除TextInputLayout包裹的输入框hint外,其余所有字符串资源均可正常跟随应用语言设置切换,涉及的布局实现代码如下:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textField2"
    android:layout_gravity="center_vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/password"
    app:startIconDrawable="@drawable/password"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    app:endIconMode="password_toggle"
    android:layout_marginTop="70dp"
    app:boxStrokeColor="@color/teal_700"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    >
    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        />
</com.google.android.material.textfield.TextInputLayout>
问题原因

这是低版本Material组件的固有特性:将android:hint配置在TextInputLayout上时,组件会在布局首次加载时缓存hint的字符串值,后续语言切换触发View重建时,缓存的旧语言值不会自动更新,最终表现为hint不跟随系统/应用语言切换。

解决方法

按实现成本从低到高排序:

  • 调整hint属性的挂载位置:将android:hint="@string/password"从TextInputLayout移到内部的TextInputEditText节点上。这是官方推荐的标准写法,TextInputLayout会自动读取子输入框的hint实现悬浮标签效果,语言切换时会随EditText的重建自动加载对应语言的资源,不会出现缓存不更新的问题,修改后的核心布局代码如下:
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textField2"
    android:layout_gravity="center_vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:startIconDrawable="@drawable/password"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    app:endIconMode="password_toggle"
    android:layout_marginTop="70dp"
    app:boxStrokeColor="@color/teal_700"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    >
    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="@string/password"
        />
</com.google.android.material.textfield.TextInputLayout>
  • 手动刷新hint值:如果业务上必须将hint配置在TextInputLayout上,可以在语言切换完成、View渲染前,手动给TextInputLayout重新赋值hint,强制刷新缓存,核心实现代码(Kotlin):
findViewById<TextInputLayout>(R.id.textField2).hint = getString(R.string.password)
  • 升级依赖版本:将应用使用的Material Components依赖升级到1.8.0及以上版本,新版本官方已经修复了hint缓存不跟随配置变更刷新的问题,无需修改原有布局或新增额外代码。

排查注意点:如果你的应用通过覆写attachBaseContext自定义资源配置实现应用内切语言,需要确保Context包装逻辑在View初始化之前执行,否则也会出现资源读取语言错误的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 12:01:15