android - 如何可靠地从 AttributeSet 中获取颜色?

标签 android xml parsing colors

我想创建一个自定义类,当在 Android XML 文件中进行布局时,该类将颜色作为其属性之一。但是,颜色可以是一种资源,也可以是多种直接颜色规范之一(例如十六进制值)。是否有使用 AttributeSet 检索颜色的简单首选方法,因为表示颜色的整数可以引用资源值或 ARGB 值?

最佳答案

假设您已经像这样定义了自定义颜色属性:

<declare-styleable name="color_view">
    <attr name="my_color" format="color" />
</declare-styleable>

然后在 View 的构造函数中,您可以像这样检索颜色:

public ColorView(Context context, AttributeSet attrs) {
   super(context, attrs);

   TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.color_view);
   try {
       int color = a.getColor(R.styleable.color_view_my_color, 0);
       setBackgroundColor(color);
   } finally {
       a.recycle();
   }
}

您实际上不必担心颜色属性是如何填充的,就像这样

<com.test.ColorView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:my_color="#F00"
    />

或者像这样:

<com.test.ColorView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:my_color="@color/red"
    />

getColor 方法在任何情况下都会返回一个颜色值。

关于android - 如何可靠地从 AttributeSet 中获取颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13512850/

相关文章:

java - String 不断调用 NullPointerException,不确定它从哪里获取

xml - 如何使用Golang将字符串转换为XML

android - Okhttp 模拟服务器不适用于 API 28 及更高版本的模拟器

android - Android 中的 UI 响应时间限制是多少?

java - 从 Java 发送 XPath 变量

xml - 从 MVC Web API 响应中删除 XML 命名空间属性

r - 解析 HPO obo 文件以提取外部参照

c# - 解析 C Sharp 中的嵌套文本

php - 帮助调试 EvalMath 的未定义偏移量

java - 两个线程交互会减慢彼此的速度吗?