2010-08-15 17 views
50

我試圖創建自定義屬性,以我的按鈕,但我不知道我必須聲明屬性使用圖像的格式...格式屬性值「機器人:可繪製的」無效

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <declare-styleable name="TCButton"> 
     <attr name="Text" format="string"/> 
     <attr name="BackgroundImage" format="android:drawable" /> 
    </declare-styleable> 


</resources> 

錯誤是格式= 「機器人:可繪製」 ......

回答

130

您可以使用格式= 「整數」,則資源ID提拉的,並AttributeSet.getDrawable(...)

這裏是一個例子。

聲明爲整數RES /價值/ attrs.xml屬性:

<resources> 
    <declare-styleable name="MyLayout"> 
     <attr name="icon" format="integer" /> 
    </declare-styleable> 
</resources> 

屬性設置爲你的佈局繪製ID:

<se.jog.MyLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    myapp:icon="@drawable/myImage" 
/> 

從屬性獲取繪製您的自定義控件組件類:

ImageView myIcon; 
//... 
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyLayout); 
Drawable drawable = a.getDrawable(R.styleable.MyLayout_icon); 
if (drawable != null) 
    myIcon.setBackgroundDrawable(drawable); 

要查看所有選項可能,請檢查android src here

+0

再看一遍,可以補充說錯誤的名稱空間聲明不會給編譯時錯誤。在本例中,如果'class MyLayout'在'se.jog.mob'中聲明,它可能看起來像'xmlns:myapp =「http://schemas.android.com/apk/res/se.jog.mob」' 。 – JOG 2011-10-31 17:29:30

+7

完成使用樣式屬性後,應該調用'a.recycle()'。 – karl 2013-06-28 17:39:12

+0

在gradle項目中,自定義模式應始終爲「http://schemas.android.com/apk/res-auto」 – 2014-07-28 12:02:27

24

我認爲這將是更好地使用它作爲一個簡單的參考:

<declare-styleable name="TCButton"> 
     <attr name="customText" format="string"/> 
     <attr name="backgroundImage" format="reference" /> 
</declare-styleable> 

,並將其設置在你的XML是這樣的:

<your.package.name.TCButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    custom:customText="Some custom text" 
    custom:backgroundImage="@drawable/myImage" 
/> 

而在你的類中設置類似的屬性這樣的:

public TCButton(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MembershipItemView, 0, 0); 

    String customText; 
    Drawable backgroundImage; 
    try { 
     customText = a.getString(R.styleable.TCButton_customText); 
     backgroundImage = a.getDrawable(R.styleable.TCButton_backgroundImage); 
    } finally { 
     a.recycle(); 
    } 

    if(!TextUtils.isEmpty(customText)) { 
     ((TextView)findViewById(R.id.yourTextView)).setText(customText); 
    } 

    if(null != backgroundImage) {      
     ((ImageView)findViewById(R.id.yourImageView)).setBackgroundDrawable(backgroundImage); 
    } 
} 

PS: 不要忘了添加此行的您使用自定義視圖的佈局的根元素

xmlns:custom="http://schemas.android.com/apk/res-auto" 

如果您未設置此選項,將無法訪問您的自定義屬性。

+1

您示例中的自定義backgroundImage屬性設置錯誤。更像是: custom:backgroundImage =「@ drawable/myImage」 – gdakram 2014-09-22 21:36:41

+0

謝謝@gdakram,我已經改正了答案。 – 2015-04-14 11:10:46

+0

很好的答案。謝謝。 – milosmns 2015-12-09 16:37:13