资源是颜色还是可绘制的?

时间:2014-01-18 22:43:38

标签: android android-resources

我创建了一个扩展ImageView的小自定义视图。 我的自定义视图提供了一种方法showError(int),我可以在其中传递资源ID,该资源ID应显示为图像视图内容。如果我可以传递一个简单的颜色资源ID或可绘制的资源ID,那就太棒了。

我的问题是:如何确定传递的资源ID是Drawable还是Color?

我目前的做法是这样的:

class MyImageView extends ImageView{

     public void showError(int resId){

        try{
            int color = getResources().getColor(resId);
            setImageDrawable(new ColorDrawable(color));
        }catch(NotFoundException e){
            // it was not a Color resource so it must be a drawable
            setImageDrawable(getResources().getDrawable(resId));
        }

     }
}

这样做是否安全?我的假设是,资源ID真的很独特。我的意思是在R.drawable或R.color中不是唯一的,但在R

中完全独特

所以没有

R.drawable.foo_drawable = 1;
R.color.foo_color = 1;

ID 1仅分配给其中一个资源而不是两者都是正确的吗?

4 个答案:

答案 0 :(得分:7)

您可能希望从资源中查找TypedValue,以便确定该值是Color还是Drawable。像这样的东西应该工作而不需要抛出并捕获异常:

TypedValue value = new TypedValue();
getResources().getValue(resId, value, true); // will throw if resId doesn't exist

// Check whether the returned value is a color or a reference
if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
    // It's a color
    setImageDrawable(new ColorDrawable(value.data));
} else if (value.type == TypedValue.TYPE_REFERENCE) {
    // It's a reference, hopefully to a drawable
    setImageDrawable(getResources().getDrawable(resId));
}

答案 1 :(得分:1)

首先,你从getResources得到的一切都是drawables。 ColorDrawable只是Drawable的子类,BitMapDrawable和其他许多(http://developer.android.com/guide/topics/resources/drawable-resource.html)也是如此。

此外,Android确保R文件中的所有值都是唯一的(因此无法获得与您所描述的值相同的值,即使它们具有不同的实例)。返回相同值的唯一情况是未找到资源时(它将返回0)。找到有关唯一ID here

的部分

希望这有帮助

答案 2 :(得分:0)

查看您的R.java文件。您将看到所有资源ID都在那里定义,每个资源都具有唯一的32位数。它们也按类型分组。例如,您应该在组中看到所有可绘制的ID:

public static final class drawable {
    public static final int my_drawable_1=0x7f020000;
    public static final int my_drawable_2=0x7f020001;

资源ID的格式为PPTTNNNN,其中PP始终为0x7f,TT为类型。我希望你的所有drawable都使用'02'作为类型,但值得检查你自己的文件。在这种情况下,如果id在0x7f020000和0x7f029999之间,你可以认为它是一个可绘制的。

答案 3 :(得分:0)

你也可以这样做

 TypedValue value = new TypedValue();

 context.getResources().getValue(resId, value, true);

// Check if it is a reference
if (value.type == TypedValue.TYPE_REFERENCE) {
    ....
 }
相关问题