一、?attr/**
這個google叫預定義樣式
這個是用在多主題時的場景,屬性值會隨着主題而改變。
但並不是一上來就可以用的,必須做足以下準備工作:
1,如果是自定義控件,請在style.xml中或attrs.xml中聲明屬性:
<declare-styleable name="SunnyAttr"> <attr name="sunnyTextColor" format="reference"/> <attr name="sunnyBgColor" format="reference"/> <attr name="sunnyTextColorWhite" format="color"/> <attr name="sunnyTextColorRed" format="reference"/> <attr name="textColor" format="reference"></attr> </declare-styleable>
如紅色字體所示,必須指明format爲reference
2,因爲attr/是跟隨Theme來變化的,所以對attr跟隨的屬性必須在Theme裏面聲明:
<!-- Base application theme. --> <style name="AppTheme" 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>
3,在對應的屬性color,drawable等裏面加入相應的資源
<color name="sunnyTextColorRed">#FFFF0000</color>
4,這樣我就可以在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等
這個就是我們平時最常用的,就是指定資源,不是動態的,不會隨着主題變化
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="紅色" android:textColor="@color/sunnyTextColorRed" />
以上,就是?attr/與@color,@drawable的一個小總結。。。。
補充:
1.使用系統參數比如colorPrimaryDark時除了以上方式,也可以這樣寫:?android:attr/colorPrimaryDark ,不過只是支持android21以及以上
2.使用自定義參數(包括系統的動態參數)在selector中引用時,android21以及以下會報以下錯誤:
<item> tag requires a 'drawable' attribute or child tag defining a drawable
是個坑啊!!