2016-09-19 24 views
2

當我嘗試在自定義drawable xml中放置一個attr時,我遇到了一個問題。如何將attr放入自定義drawable中?

這裏是我的佈局的樣本:

 <Button 
      android:id="@+id/btn" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:background="@drawable/my_custom_btn"/> 

然後我的自定義繪製 「my_custom_btn」,我想與attr_my_custom_color指定其顏色:

<?xml version="1.0" encoding="utf-8"?> 
    <selector xmlns:android="http://schemas.android.com/apk/res/android"> 
     <item android:state_pressed="true" 
      android:drawable="?attr/attr_my_custom_color" /> <!-- pressed --> 
    </selector> 

我attr.xml文件:

<resources> 
    <attr name="attr_my_custom_color" format="color"/> 
</resources> 

而我的style.xml文件,我的appli陽離子使用此主題(在我的清單):當我在我的佈局測試

<resources> 
<style name="AppThemeTest" parent="Theme.AppCompat.Light.NoActionBar"> 

    <item name="attr_my_custom_color">@color/primary</item> 

</style> 

我ATTR工作正常,但是當我把它放在我的自定義繪製裏面,這是行不通的。

它編譯罰款,但是當我啓動我的應用程序,它會顯示這個錯誤:

造成的:org.xmlpull.v1.XmlPullParserException:二進制XML文件行#4:標籤需要「繪製」屬性或子標籤定義一個可繪製的

你能幫我指定一個自定義drawable裏面的attr嗎?

回答

0
you have to change background to drawable 


<Button 
     android:id="@+id/btn" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:drawable ="@drawable/my_custom_btn"/> 
+0

它不會崩潰了,但它並不適用'<項目的android:state_pressed = 「真」 機器人:可繪製= 「?ATTR/attr_my_custom_color」/><! - 按 - > 「要麼。 – curiousStranger123

+0

你的minSdkVersion是什麼? –

+0

minSdkVersion 16 – curiousStranger123

相關問題