以编程方式设置 TextInputLayout 提示文本颜色和浮动标签颜色

Programmatically set TextInputLayout Hint Text Color and Floating Label Color

我使用 TextInputLayout,如果输入字段是必需的,我想以编程方式设置提示文本颜色和浮动标签颜色。在移动到 TextInputLayout 之前,我曾经使用以下

以编程方式设置提示文本颜色

textField.setHintTextColor(Color.RED);

谁能指导我如何以编程方式为 TextInputLayout 设置提示文本颜色和浮动标签颜色。

在所附的屏幕截图中,我希望提示文本 Address 1 在未聚焦时显示为红色,并且在聚焦时浮动标签 Address 1 应该是红色的。

请仔细阅读此处的文档:TextInputLayout Methods

有一个方法:

setHintTextAppearance(int resId)

它需要一个可能是样式资源的资源 ID!

我会试试看效果如何!

希望对您有所帮助!

我能够使用以下方法获得红色的 FloatingLabel

textInputLayout.setErrorEnabled(true);
textInputLayout.setError(" ");

我用反射改变了聚焦颜色。这是可能对某人有帮助的片段。

private void setUpperHintColor(int color) {
    try {
        Field field = textInputLayout.getClass().getDeclaredField("mFocusedTextColor");
        field.setAccessible(true);
        int[][] states = new int[][]{
                new int[]{}
        };
        int[] colors = new int[]{
                color
        };
        ColorStateList myList = new ColorStateList(states, colors);
        field.set(textInputLayout, myList);

        Method method = textInputLayout.getClass().getDeclaredMethod("updateLabelState", boolean.class);
        method.setAccessible(true);
        method.invoke(textInputLayout, true);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

编辑 2018-08-01:

如果您使用的是设计库 v28.0.0 及更高版本,字段已从 mDefaultTextColor 更改为 defaultHintTextColor,从 mFocusedTextColor 更改为 focusedTextColor

检查反编译 class 其他字段。

通常 TextInputLayout 提示文本颜色来自应用的 colorAccent。

但如果您想更改,则可以使用样式。

<android.support.design.widget.TextInputLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:theme="@style/TextLabel">
 </android.support.design.widget.TextInputLayout>

@style

<style name="TextLabel" parent="TextAppearance.AppCompat">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">@color/Color Name</item> 
    <item name="android:textSize">20sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">@color/Color Name</item>
    <item name="colorControlNormal">@color/Color Name</item>
    <item name="colorControlActivated">@color/Color Name</item>
 </style>

但是如果你想添加红色那么你如何区分错误颜色意味着基本标准错误有红色。

textField.setHintTextColor(Color.RED); Can someone guide me on how to set the hint text color and the floating label color programmatically for a TextInputLayout.

setHintTextColor 适用于 API 23+

用于更改 TextInput 布局的 Focused ColorDefault Text Color

private void setInputTextLayoutColor(int color, TextInputLayout textInputLayout) {
    try {
        Field field = textInputLayout.getClass().getDeclaredField("mFocusedTextColor");
        field.setAccessible(true);
        int[][] states = new int[][]{
                new int[]{}
        };
        int[] colors = new int[]{
                color
        };
        ColorStateList myList = new ColorStateList(states, colors);
        field.set(textInputLayout, myList);

        Field fDefaultTextColor = TextInputLayout.class.getDeclaredField("mDefaultTextColor");
        fDefaultTextColor.setAccessible(true);
        fDefaultTextColor.set(textInputLayout, myList);

        Method method = textInputLayout.getClass().getDeclaredMethod("updateLabelState", boolean.class);
        method.setAccessible(true);
        method.invoke(textInputLayout, true);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

编辑: 更改 AppCompactEditText 线条颜色

您需要将 EditText 上的 backgroundTintList(或 supportBackgroundTintList)设置为 ColorStateList 的实例,其中仅包含您希望将色调更改为的颜色.以向后兼容的方式执行此操作的简单方法如下所示:

ColorStateList colorStateList = ColorStateList.valueOf(color)
editText.setSupportBackgroundTintList(colorStateList)

这将为 EditText 提供所需的下划线颜色。

让我分享一下我的经验。我还尝试了与该问题相关的每个相关问题中给出的所有解决方案。即 将子小部件的提示颜色更改为 TextInputLayout

很高兴能稍微详细地分享一下这个问题的答案。

我们需要知道的是:-

  1. 将下行添加到 TextInputLayout 或其子小部件的样式中并没有多大帮助。

    @color/white

    因为只要焦点 received/granted 到可编辑小部件,它就会使用 colorAccent。

  2. 这个问题的实际答案是在应用程序的样式标签中添加该样式行,当那个或任何可编辑区域不在焦点时,它会设置提示颜色。 (这就是我们每次都错过的重点)。

如果我们有这方面的其他信息,请告诉我。

谢谢!

通过 Material Components library 您可以使用:

布局中:

<com.google.android.material.textfield.TextInputLayout
    app:hintTextColor="@color/mycolor"
    android:textColorHint="@color/text_input_hint_selector"
    .../>

风格:

<style name="..." parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
    <!-- The color of the label when it is collapsed and the text field is active -->
    <item name="hintTextColor">?attr/colorPrimary</item>
    <!-- The color of the label in all other text field states (such as resting and disabled) -->
    <item name="android:textColorHint">@color/mtrl_indicator_text_color</item>
</style>

代码中:

// Sets the text color used by the hint in both the collapsed and expanded states
textInputLayout.setDefaultHintTextColor(...);

//Sets the collapsed hint text color
textInputLayout.setHintTextColor(....);

我遇到了完全相同的问题,但具有可变提示和彩色符号。我通过数据绑定和 Spannable 以这种方式完成了这个技巧。

 <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/ti_last_name"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="4dp"
                android:layout_marginEnd="8dp"
                app:boxStrokeWidth="0dp"
                app:boxStrokeWidthFocused="0dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/et_last_name"
                    style="@style/EditText"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:onFocusChangeListener="@{viewModel.onFocusChangeListener(@string/last_name)}"
                    tools:hint="@string/last_name" />
</com.google.android.material.textfield.TextInputLayout>

viewModel.onFocusChangeListener这样定义

    fun onFocusChangeListener(hint: String) =
        OnFocusChangeListener { view, isFocused ->
            (view.parent.parent as TextInputLayout).apply {
                val editText = (view as TextInputEditText)
                if (isFocused) {
                    this.hintTextColor = ColorStateList.valueOf(this.getColor(R.color.black))
                    editText.hint = ""
                    this.hint = hint
                } else {
                    if (!editText.text.isNullOrBlank()) {
                        this.defaultHintTextColor = ColorStateList.valueOf(this.getColor(R.color.black))
                        editText.hint = ""
                        this.hint = hint
                    } else {
                        this.hintTextColor = ColorStateList.valueOf(this.getColor(R.color.hint_color))
                        val builder = SpannableStringBuilder()
                        builder.append(hint)
                        val start = builder.length
                        val end = start + 1
                        builder.append("\u2981")
                        builder.setSpan(
                            ForegroundColorSpan(Color.RED),
                            start,
                            end,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        builder.setSpan(
                            SuperscriptSpan(),
                            start,
                            end,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        editText.hint = builder
                        this.hint = ""
                    }
                }
            }

        }

它允许对 focused/not 焦点状态使用不同的提示和颜色,并且具有彩色跨度。

this.getColor()只是扩展

 fun View.getColor(color: Int): Int {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        this.context.resources.getColor(color, context.theme)
    } else {
        this.context.resources.getColor(color)
    }