Change the TextInputLayout outline box color programmatically

Issue

I would like to change outline of the TextInputLayout programmatically, but I cannot seem to get it to work. There is an option to do it via XML (question by other SO user using XML), but that is unusable for me as I need to have dynamic coloring. I currently have the following layout:

<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:id="@+id/color_outline"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/color"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Choose color"/>

</com.google.android.material.textfield.TextInputLayout>

I’ve attempted to apply coloring by looking at the various box methods of the TextInputLayout, but it did not have any effect.

internal fun String.toIntColor() = Integer.parseInt(this.replaceFirst("#", ""), 16)


val colorOutline: TextInputLayout = view.findViewById(R.id.color_outline)
colorOutline.boxStrokeColor = "#006699".toIntColor()

How can I color it dynamically, like in the picture below?

Current situation:
enter image description here

Desired situation: (photoshopped)
enter image description here

Similar question, but focussing on XML

Solution

You can the method setBoxStrokeColorStateList.

Something like:

//Color from rgb
int color = Color.rgb(255,0,0);
//Color from hex string
int color2 = Color.parseColor("#FF11AA");

int[][] states = new int[][] {
        new int[] { android.R.attr.state_focused}, // focused
        new int[] { android.R.attr.state_hovered}, // hovered
        new int[] { android.R.attr.state_enabled}, // enabled
        new int[] { }  // 
    };

    int[] colors = new int[] {
        color,
        color,
        color,
        color2
    };

    ColorStateList myColorList = new ColorStateList(states, colors);
    textInputLayout.setBoxStrokeColorStateList(myColorList);

enter image description here

Answered By – Gabriele Mariotti

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *