我刚试过这个:
val foo = mapOf("a" to "Red")
someView.setBackgroundColor(Color.parseColor(foo["a"]))
它运行良好,你能分享更多关于异常的细节吗?
更新
我尝试完全按照所写的方式使用您的 MyClass,但我已将 a 的值替换为 Red 而不是您的 b 字符串。
您是否正确使用parseColor?
/**
* </p>Parse the color string, and return the corresponding color-int.
* If the string cannot be parsed, throws an IllegalArgumentException
* exception. Supported formats are:</p>
*
* <ul>
* <li><code>#RRGGBB</code></li>
* <li><code>#AARRGGBB</code></li>
* </ul>
*
* <p>The following names are also accepted: <code>red</code>, <code>blue</code>,
* <code>green</code>, <code>black</code>, <code>white</code>, <code>gray</code>,
* <code>cyan</code>, <code>magenta</code>, <code>yellow</code>, <code>lightgray</code>,
* <code>darkgray</code>, <code>grey</code>, <code>lightgrey</code>, <code>darkgrey</code>,
* <code>aqua</code>, <code>fuchsia</code>, <code>lime</code>, <code>maroon</code>,
* <code>navy</code>, <code>olive</code>, <code>purple</code>, <code>silver</code>,
* and <code>teal</code>.</p>
*/
@ColorInt
public static int parseColor(@Size(min=1) String colorString) {
if (colorString.charAt(0) == '#') {
// Use a long to avoid rollovers on #ffXXXXXX
long color = Long.parseLong(colorString.substring(1), 16);
if (colorString.length() == 7) {
// Set the alpha value
color |= 0x00000000ff000000;
} else if (colorString.length() != 9) {
throw new IllegalArgumentException("Unknown color");
}
return (int)color;
} else {
Integer color = sColorNameMap.get(colorString.toLowerCase(Locale.ROOT));
if (color != null) {
return color;
}
}
throw new IllegalArgumentException("Unknown color");
}
更新 2:
好的,你说的是“一个扩展 RecyclerView.ViewHolder 的类”,但所说的类只是 RecyclerView 类中的一个抽象类,所以它里面没有 setBackgroundColor,除非你正在做类似的事情:
yourViewHolderInstance.itemView.setBackgroundColor.
那么你的 setBackgroundColor 的签名是什么?
看起来像public void setBackgroundColor(@ColorInt int color) { 吗?
我只是为了好玩才将它添加到我的应用程序中:
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as BaseViewHolder).bind(getItem(position))
// For Filippo :)
holder.itemView.setBackgroundColor(Color.parseColor(MyClass.foo["a"]))
}
嗯……现在一切看起来都很红。 :)
更新 3
好的,根据您上次的更新,您是从 Java 调用它,因此您不能使用 Kotlin 语法...
这样做:
final Map<String, String> foo = MyClass.foo;
yourView.setBackgroundColor(Color.parseColor(foo.get("a")));
显然,您可以避免中间分配并继续:
v.setBackgroundColor(Color.parseColor(MyClass.foo.get("a")));
我通常更喜欢前者,特别是如果你给它所有有意义的名字并且需要调试,但就我而言并没有真正的区别。