如何可靠地从AttributeSet中获取颜色? [英] How can I reliably get a color from an AttributeSet?

查看:125
本文介绍了如何可靠地从AttributeSet中获取颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a custom class that takes a color as one of its attributes when laid out in an Android XML file. However, a color could be a resource or it could be one of a number of direct color specifications (eg a hex value). Is there a simple preferred method for using AttributeSet to retrieve the color, since an integer representing a color could refer either to a resource value or an ARGB value?

推荐答案

假设您已经定义了自定义颜色属性,如下所示:

Let's say you have defined your custom color attribute like this:

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

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

Then in the constructor of your view, you can retrieve the color like this:

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();
   }
}

您实际上不必担心如何填充color属性,就像这样

You don't actually have to worry how the color attribute was populated, either like this

<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方法都将返回颜色值.

The getColor method will return a color value in any case.

这篇关于如何可靠地从AttributeSet中获取颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆