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

如何在TextInputLayout中实现Label提示文本的水平居中?

TextInputLayout Label提示文本水平居中方案

针对Material组件库的TextInputLayout,可通过以下两种方式实现Label提示文本水平居中,同时覆盖悬浮态、非悬浮态两种显示场景:


方法1:XML静态配置(推荐)

  • 第一步:在res/values/styles.xml中添加自定义hint样式
    <style name="CenteredLabelStyle" parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
        <item name="android:gravity">center_horizontal</item>
        <item name="android:textAlignment">center</item>
    </style>
    
  • 第二步:在布局文件中给TextInputLayout和内部输入框配置对应属性
    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:hintEnabled="true"
        app:hintTextAppearance="@style/CenteredLabelStyle">
    
        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="提示文本"
            android:gravity="center_horizontal"/>
    
    </com.google.android.material.textfield.TextInputLayout>
    

方法2:代码动态修改

如果需要运行时动态调整居中属性,可使用以下代码:

// Kotlin示例
textInputLayout.hintTextAppearance = R.style.CenteredLabelStyle
textInputEditText.gravity = Gravity.CENTER_HORIZONTAL
// Java示例
textInputLayout.setHintTextAppearance(R.style.CenteredLabelStyle);
textInputEditText.setGravity(Gravity.CENTER_HORIZONTAL);

注意:Material Components 1.1.0及以上版本无需额外配置其他属性,上述方案即可兼容所有Label显示状态的居中效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:15:04