20
有了這個自定義視圖MyView
用於繪製參考資源ID我定義了一些自定義屬性:獲得風格的屬性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="normalColor" format="color"/>
<attr name="backgroundBase" format="integer"/>
</declare-styleable>
</resources>
,並指定他們在佈局XML如下:
<com.example.test.MyView
android:id="@+id/view1"
android:text="@string/app_name"
. . .
app:backgroundBase="@drawable/logo1"
app:normalColor="@color/blue"/>
起初我以爲我可以檢索自定義屬性backgroundBase
使用:
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int base = a.getInteger(R.styleable.MyView_backgroundBase, R.drawable.blank);
只有在未分配屬性且返回默認R.drawable.blank
時才起作用。
當app:backgroundBase
被分配了一個異常被拋出「無法轉換爲整數類型= 0xn」因爲,即使自定義屬性的格式聲明爲整數,它確實引用了Drawable
,應作如下檢索:
Drawable base = a.getDrawable(R.styleable.MyView_backgroundBase);
if(base == null) base = BitMapFactory.decodeResource(getResources(), R.drawable.blank);
這個工程。
現在我的問題:
我真的不想從TypedArray得到Drawable
,我想對應app:backgroundBase
整數ID(在上面的例子中這將是R.drawable.logo1
)。我怎麼才能得到它?
一些澄清,將幫助我:'R.drawable.blank'是在情況下,默認的資源請求不存在 – HaydenKai 2016-12-16 09:50:07