布局文件中資源引用的寫(xiě)法多種多樣,且看以background舉例:
<
……
android:background="@color/colorPrimary"
android:background="@com.demo.app:color/colorPrimary"
android:background="?colorPrimary"
android:background="?attr/colorPrimary"
android:background="?com.demo.app:attr/colorPrimary"
android:background="?com.demo.app:colorPrimary"
android:background="?android:colorPrimary"
android:background="?android:attr/colorPrimary"
……
>
懵ing。。。。那么接下來(lái)就詳細(xì)說(shuō)說(shuō),這些都代表了什么
理解 @ 和 ?
首先我們需要理解@和?分別引用的是什么內(nèi)容
@ :引用資源(resources)
? :引用樣式屬性(style attribute)
詳細(xì)來(lái)講:
-
使用@ 是引用一個(gè)具體的值比如color, string, dimension 等等這些具體的某個(gè)值。不管activity是什么主題的,@引用的值都不會(huì)改變。
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> </resources> -
? 是引用一個(gè)style attribute,其值取決于當(dāng)前使用的主題。值為當(dāng)前主題下定義的屬性值:
<resources> <style name="AppTheme" parent="Theme.AppCompat.Light"> <item name="colorPrimary">#3F51B5</item> </style> </resources> …… <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="?colorPrimary"/>這樣,TextView的背景色就是當(dāng)前主題下定義的colorPrimary
語(yǔ)法
引用resources (@)
@[包名:]資源類(lèi)型/資源名
- 包名:可省略,即這個(gè)資源所屬的package,默認(rèn)就是你app的包名,還有一個(gè)預(yù)留的包——android,使用系統(tǒng)發(fā)布的資源。
- 資源類(lèi)型:R的子集,即資源的類(lèi)型(color, string, dimen等等)
- 資源名:我們要引用的資源的名稱(chēng)
例如:
<……
android:background="@color/colorPrimary"
android:background="@com.myapp:color/colorPrimary"
……>
這兩種寫(xiě)法是等效的:
- package(可不寫(xiě)) = com.myapp
- 資源類(lèi)型 = color
- 資源名 = colorPrimary
那么使用系統(tǒng)預(yù)定義的資源就是:
<……
android:background="@android:color/holo_orange_dark"
……>
這個(gè)例子拆解開(kāi)來(lái)就是:
- package = android – 引用內(nèi)置的資源
- 資源類(lèi)型 = color
- 資源名 = holo_orange_dark
PS:
使用AppCompat定義的資源的資源時(shí),常見(jiàn)以下的寫(xiě)法:
android:background="?selectableItemBackground"
我們并沒(méi)有定義這些資源,也沒(méi)有使用預(yù)留包名,之所以能這樣使用是因?yàn)锳ppCompat那些資源被整合到了app中,不需要使用android關(guān)鍵字來(lái)引用。
引用樣式屬性(?)
語(yǔ)法與@相似
?[包名:][資源類(lèi)型/]資源名稱(chēng)
區(qū)別在于,資源類(lèi)型也是可不寫(xiě)的,因?yàn)檫@里唯一允許的資源類(lèi)型是attr。
下面的表述方式其實(shí)完全是一樣的:
<
android:background="?com.demo.app:attr/colorPrimary" //完整寫(xiě)法
android:background="?com.demo.app:colorPrimary" //省略attr
android:background="?attr/colorPrimary" //省略包名
android:background="?colorPrimary" // 省略包名和 attr
>