Reputation: 1698
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?
Desired situation: (photoshopped)
Similar question, but focussing on XML
Upvotes: 4
Views: 5152
Reputation: 308
In Kotlin I have modified the @Gabriele's answer to make it working for me
You can define an extension function as :
private fun TextInputLayout.setBoxStrokeColorSelector() {
//Color from rgb
int color = Color.rgb(255,0,0);
//Color from hex string
val defaultColor = ContextCompat.getColor(context,R.color.indicator_def)
val states = arrayOf {
intArrayOf(android.R.attr.state_focused), // focused
// intArrayOf(android.R.attr.state_hovered), // hovered
intArrayOf(android.R.attr.state_enabled), // enabled
intArrayOf() // default
}
val colors = intArrayOf(color, // focused color
/*color,*/ // hovered color
color, // enabled color
defaultColor) // default color
val myColorList = ColorStateList(states, colors)
setBoxStrokeColorStateList(myColorList)
}
and just call it for any TextInputLayout in your app like
TextInputLayout.setBoxStrokeColorSelector(ContextCompat.getColor(this, R.color.colorPrimary))
Upvotes: -1
Reputation: 365038
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);
Upvotes: 11