android - 以编程方式更改 TextInputLayout 轮廓框颜色
问题描述
我想以编程方式更改 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()
如何动态着色,如下图所示?
解决方案
你可以的方法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);
推荐阅读
- mysql - 如何在laravel eloquent的whereMonth方法中传递数组
- python - root.withdraw 不适用于 if 语句?
- vue.js - Vue Bootstrap b-table 懒加载数据
- python - 将 Python 代码更改为 Node.js 代码(base64 / hmac256 编码)
- javascript - 发送后如何删除消息?
- css - 需要帮助重新调整 CSS 滑动文本动画的用途
- android - 如何解决 Flutter Camera 插件 stopVideoRecording 方法的异常?
- r - R:获取p个二进制变量的所有组合
- python - 如何用其中一个键修改 dict
- scala - Spark,检查某些列是否为 True,然后用 Y 或 N 填充新列