在 Android 項(xiàng)目開發(fā)中,我們經(jīng)常會(huì)用 “@” 或者 “?” 符號(hào)去引用系統(tǒng)或者我們應(yīng)用內(nèi)添加的資源胁澳,這兩種符號(hào)的引用有什么區(qū)別呢,“?attr/” 與 “?android:attr/” 之間又有怎樣的不同呢?本文我們不妨閑聊一下米者。
“@” 與 “?” 符號(hào)的引用在使用時(shí)都有一個(gè)規(guī)范的格式:"@[+][package:]type:name"韭畸,"?[package:][type:]name"÷悖可以看到胰丁,二者均包含引用符號(hào)、資源所屬的包喂分、資源類型和資源名稱锦庸。
@ 資源引用
“@” 符號(hào)用于引用系統(tǒng)和我們?cè)陧?xiàng)目中添加的一些固有資源(drawable,string 等)蒲祈,或者定義的 style 樣式甘萧。比如:
android:text="@string/app_name" ```
這里的 app_name 就是我們自己定義在項(xiàng)目文件 values/strings.xml 中的字符串資源。
android:text="@android:string/cancel" ```
而這里的 cancel 屬于 Android SDK 中的系統(tǒng)字符串資源梆掸,所以需要添加@android: 來(lái)指明引用來(lái)源扬卷。android: 是 package: 的一個(gè)具體實(shí)例。
? 屬性引用
“?” 符號(hào)用于引用當(dāng)前主題中定義的一些屬性值酸钦。注意怪得,“?” 符號(hào)通過(guò)屬性名字間接引用當(dāng)前主題中的對(duì)應(yīng)屬性值,而不是屬性本身卑硫。舉個(gè)例子:
android:divider="?android:listDivider" ```
這里的 “?” 符號(hào)通過(guò)屬性名 android:listDivider 間接獲取當(dāng)前主題賦予該屬性的值徒恋。如同 @android: 一般,?android: 表示該值源自 Android SDK 系統(tǒng)屬性拔恰。由于在當(dāng)前主題中尋找對(duì)應(yīng)屬性名的值因谎,所以沒有指定屬性類型基括,其實(shí)等同于:?android:attr/listDivider颜懊。
那如何引用項(xiàng)目中自定義的屬性呢?我們?cè)?attrs.xml 中定義一個(gè)屬性,如:
<declare-styleable name="CustomTextView">
<attr name="colorTextCustom" format="reference|color"/>
</declare-styleable> ```
顯然,此時(shí)我們定義的 colorTextCustom 屬性是沒有值的河爹,直接引用沒有任何作用匠璧。需要在主題 style 中賦值:
<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorTextCustom">#FF0000</item>
</style>
<style name="AppTheme" parent="BaseTheme">
<item name="android:textColor">?colorTextCustom</item>
</style> ```
可以看到,這里在 BaseTheme 中對(duì) colorTextCustom 屬性賦值咸这,并在 AppTheme 中通過(guò) “?colorTextCustom” 引用該屬性值夷恍。由于是本地項(xiàng)目中定義的屬性,所以沒有添加 android: 命名空間媳维。其實(shí)酿雪,這種做法的好處是,AppTheme 所覆蓋的 View 均可通過(guò)構(gòu)造函數(shù)獲取當(dāng)前主題中的 colorTextCustom 屬性值侄刽。
**R.attr & R.style**
Android SDK 中定義有很多屬性和主題可供使用指黎,詳見官方文檔:R.attr &R.style。使用系統(tǒng)資源的好處就是州丹,滿足不同系統(tǒng)的適配需求醋安,較為靈活。
這里舉幾個(gè)常用的:
style="?android:attr/borderlessButtonStyle"```
Android 5.0 默認(rèn) Button 的樣式自帶邊框陰影墓毒,可以使用這個(gè)系統(tǒng)樣式去除該樣式吓揪。當(dāng)然,這是單獨(dú)設(shè)置時(shí)的操作所计,為了方便全局控制柠辞,可以在 styles.xml 中自定義一個(gè)樣式,繼承一個(gè)無(wú)邊框樣式作為 parent:
<style name="CustomBorderlessButtonStyle" parent="@style/Widget.AppCompat.Button.Borderless">
<item name="android:textColor">@android:color/white</item>
...
</style> ```
**android:background="?android:attr/selectableItemBackground"**
可用于設(shè)置一些 List Item主胧、Button之類帶點(diǎn)擊效果的背景钾腺。該樣式自帶觸摸點(diǎn)擊效果,在 5.0 和更高版本上讥裤,更是附有 Ripple 漣漪效果放棒,省去我們自己實(shí)現(xiàn) selector 選擇器的過(guò)程。當(dāng)然我們也可以自己使用 <ripple> 標(biāo)簽定義一個(gè) drawable 文件實(shí)現(xiàn)漣漪效果己英,只是需要注意版本限制间螟。
**android:background="?android:attr/dividerVertical"**
實(shí)現(xiàn)分割線背景。
還有一些其他有用的系統(tǒng)資源损肛,這里就不一一列舉了...