簡體   English   中英

資源是顏色還是可繪制的?

[英]Is resource a color or a drawable?

我創建了一個擴展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分配給其中一個資源但不分配給兩個資源?

您可能希望從資源中查找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));
}

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

此外,Android確保R文件中的所有值都是唯一的(因此不可能像您描述的那樣獲得相同的值,即使它們具有不同的實例)。 返回相同值的唯一情況是未找到資源時(它將返回0)。 此處查找有關唯一ID的部分

希望這可以幫助

查看您的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之間,您可以假設它是可繪制的。

你也可以這樣做

 TypedValue value = new TypedValue();

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM