以编程方式更改TextInputLayout的轮廓框颜色

4
我希望能够通过编程方式更改TextInputLayout的轮廓线,但似乎无法实现。有一种通过XML进行操作的选项(其他SO用户使用XML提出的问题),但对我来说不可用,因为我需要动态着色。目前我拥有以下布局:
<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>

我尝试通过查看 TextInputLayout 的各种框方法来应用颜色,但没有任何效果。

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


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

如何动态着色,就像下图所示?
当前情况:
enter image description here 期望情况:(photoshopped)
enter image description here 类似的问题,但集中在XML上
2个回答

10

您可以使用方法setBoxStrokeColorStateList

类似这样:

//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);

在此输入图片描述


2
它似乎确实是最近添加的,感谢您迅速的通知。我会将其标记为答案 :) - Jason

-1
在 Kotlin 中,我修改了 @Gabriele 的答案以使其适用于我的情况。
你可以定义一个扩展函数如下:
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)
}

只需在您的应用中任何 TextInputLayout 中调用它即可

TextInputLayout.setBoxStrokeColorSelector(ContextCompat.getColor(this, R.color.colorPrimary))

这不是有效的 Kotlin 语法。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接