1. 程式人生 > >android中?attr/**與@drawable/**或@color/**等的區別

android中?attr/**與@drawable/**或@color/**等的區別

今天在寫一個Demo,研究主題的時候,遇到了【?attr/colorPrimary】這個用法,由於網上都是千篇一律的回答,所以我只能硬著頭皮去看原始碼了,茶壺煮餃子,暫且記下來,作為備忘錄吧。 一、?attr/**  這個Google把它叫做“預定義樣式”,字面意思就是“預先定義好的樣式”。也就是相當於給這個樣式定義一個變數,隨後是可以進行賦值的。 用的最多的場景就是自定義控制元件了,比如我現在需要自定義一個控制元件,要求它的字型顏色是可以動態修改的。此時,我們可以這樣做: - 第一步:在attrs.xml中宣告一個屬性:<declare-styleable name="SunnyAttr">   </declare-styleable>
- 第二步:指定屬性的名字及 屬性值的型別
<declare-styleable name="SunnyAttr"> <attr name="sunnyTextColor" format="reference"/> <attr name="sunnyTextColorWhite" format="color"/></declare-styleable>屬性值 的型別有以下幾種: 1. reference: 指參考指定Theme中的資源ID(比如:@string/test) 2. color:指顏色值(比如:#FFFF0000) 3. boolean: 布林值(比如:true) 4.
dimension:尺寸(比如:100dp) 5. float:浮點型(比如:0.3) 6. integer:整型(比如:1) 7. string:字串 8. fraction:百分數(比如:100%) 9. flag:或運算(比如:0x10 | 0x11) 10. enum:列舉
- 第三步:由於從原始碼裡面窺探出,attr/是跟隨Theme來變化的,因此我們可以定義一個繼承自Android系統某一主題的主題樣式:
<style name="SunnyTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style>
- 第四步:在自定義主題裡面,再定義一個供外面呼叫的屬性名,並賦值:
<style name="SunnyTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!--定義一個供外面引用的屬性名,並賦值--> <item name="sunnyTextColorRed">@color/sunnyTextColorYellow</item></style>- 第五步:最後我們在xml中使用自定義控制元件的自定義屬性時,就可以為它賦值了:<com.smartbracelet.sunny.sunnydemo3.SunnyTextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="設定介面" app:sunnyTextColor="?attr/sunnyTextColorRed" /> 二、@color,@drawable 說完?attr/,再看@color與@drawable,後面2個是我們平時最常用的,就是指定資源,不是動態的,不會隨著主題變化<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="紅色" android:textColor="@color/sunnyTextColorRed" />以上,就是?attr/與@color,@drawable的一個小總結。。。。