Android訪問資源與屬性之 ? , @
在Android xml中訪問資源和樣式屬性的語法有著固定的格式,但是也有些靈活變化。
比如通過xml布局設(shè)置一個view
的background color
的幾種方法:
android:background="@color/colorPrimary"
android:background="@com.myapp:color/colorPrimary"
android:background="?colorPrimary"
android:background="?attr/colorPrimary"
android:background="?com.myapp:attr/colorPrimary"
android:background="?com.myapp:colorPrimary"
android:background="?android:colorPrimary"
android:background="?android:attr/colorPrimary"
上面這些語法主要區(qū)別是對資源的訪問和對樣式屬性的訪問,詳細可參考Android開發(fā)官網(wǎng)
引用資源(resources) 與 引用樣式屬性(style attribute) 的區(qū)別
@
引用資源 (resources)
使用@
語法引用資源時,是在訪問一個實際的值(官網(wǎng)上標題使用 Accessing Resouces),這個資源必須有具體的值,我們能明確的知道自己使用的是哪個具體值。
比如定義了一個color
資源:
.../values/color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#5F51B5</color/
</resources>
然后在xml中引用這個資源android:background="@color/colorPrimary"
,那么不管Activity是什么主題,background
的值始終是確定值#5F51B5
?
引用樣式屬性 (style attribute)
使用?
語法時,表示嘗試引用一個樣式屬性(Referencing style attributes),具體的值取決于當前使用的主題。在特定的主題下,可以重寫這個屬性,因此不需要改變xml主題,只需要應(yīng)用恰當?shù)闹黝},background
具體值就改變了。
<resource>
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">#F0A</item>
</style>
</resource>
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?colorPrimary"
在這種情況下,我們詢問Android:“嘿,把當前主題下定義的colorPrimary
屬性的值給我”。所以我們很難告訴你background
到底會是什么顏色,因為它取決于這個布局所屬的activity
所應(yīng)用的主題。
語法
引用資源 (@)
在xml中引用一個資源使用下面這個語法:
@[<package_name>:]<resource_type>/<resource_name>
-
<package_name>
引用資源所在包的包名,** 如果在同一個包下引用,不是必須的; 使用android
表示使用系統(tǒng)資源 ** -
<resource_type>
R
類的子集,即資源的類型(attr
,color
,string
,dimen
等等) -
<resource_name>
資源名稱,可以是不帶后綴的資源文件名或者定義在xml中的資源
引用樣式屬性 (?)
?[<package_name>:][<resource_type>/]<resource_name>
引用樣式屬性語法和引用資源除了前綴是?
,其他是一樣的,其中<resource_type>/
是個可選項,因為引用樣式屬性唯一的資源類型是attr
,android打包工具允許我們省略資源類型。
所以從Android角度來看,下面的表述方式是完全一樣的:
android:background="?com.myapp:attr/colorPrimary" // verbose format
android:background="?com.myapp:colorPrimary" // attr is skipped since its optional
android:background="?attr/colorPrimary" // package is skipped since its optional
android:background="?colorPrimary" // package & attr is skipped
引用系統(tǒng)樣式屬性:?android:colorPrimary