How to set TextInputLayout error message colour?

前端 未结 9 2155
旧巷少年郎
旧巷少年郎 2020-11-27 13:58

How can I change the colour of the error message that can be set to appear below the text field in a TextInputLayout (via setError(...) – see error

相关标签:
9条回答
  • 2020-11-27 14:41

    Create a custom style which uses @android:style/TextAppearance as parent in your styles.xml file:

    <style name="error_appearance" parent="@android:style/TextAppearance">
        <item name="android:textColor">@color/red_500</item>
        <item name="android:textSize">12sp</item>
    </style>
    

    And use it in your TextInputLayout widget:

     <android.support.design.widget.TextInputLayout
                android:id="@+id/emailInputLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:errorTextAppearance="@style/error_appearance">
    

    error example

    Edit: Set the hint on the object, which is inside your TextInputLayout (EditText, TextView, etc.) to hold different colors for the hint and the error.

    0 讨论(0)
  • 2020-11-27 14:46

    Actually, to change just the error message color, you can set textColorError in your theme (and also set colorControlNormal and colorControlActivated for the general widget and hint text color). TextInputLayout picks up that attribute. NOTE: if you set errorTextAppearance to a custom style then textColorError will have no effect.

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorControlNormal">@color/control_normal</item>
        <item name="colorControlActivated">@color/control_activated</item>
        <item name="textColorError">@color/error</item>
        <!-- other styles... -->
    </style>
    

    And in your AndroidManifest.xml:

    <application
        android:theme="@style/AppTheme"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
    
        <!-- ... -->
    
    </application>
    
    0 讨论(0)
  • 2020-11-27 14:50

    UPDATE

    Please use a custom view instead and not this


    A modded version of @jared's Answer which works in my case :

    public static void setErrorTextColor(TextInputLayout textInputLayout, int color) {
        try {
            Field fErrorView = TextInputLayout.class.getDeclaredField("mErrorView");
            fErrorView.setAccessible(true);
            TextView mErrorView = (TextView)fErrorView.get(textInputLayout);
            mErrorView.setTextColor(color);
            mErrorView.requestLayout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
提交回复
热议问题