android系统中引用资源有几种方式,常用的有“@”“@+”引用具体资源的方式。也有“?”"?attr"等引用主题属性的方式,方式多了容易乱,为保持思路清晰,总结之。

引用格式分解:

android:background="@color/light_red" 引用colors.xml中定义的颜色资源

android:background="?attr/colorPrimary" 引用主题属性colorPrimary


android命名空间background属性名称@表明引用的是具体资源?表明引用的是系统属性color资源类型attr属性的类型light_redcolors.xml中定义的颜色资源名称colorPrimary属性名称


引用具体资源:

1、引用自定义资源

格式:@[package:]type/name

例如:android:text="@string/app_name"

=====================================================================

2、引用系统资源

格式:@android:type/name

例如:android:textColor="@android:color/light_blue"

@android:style/Theme.Holo.Light //引用系统主题

3、“@+”表示新建并引用资源id

例如:android:id="@+id/bt_title"

继承关系指定:(这里可以不需要使用“@”)

<style name="AppTheme" parent="android:Theme.Holo.Light" />

同上<style name="AppTheme" parent="@android:style/Theme.Holo.Light">

<style name="AppTheme" parent="Theme.AppCompat.Light" />

同上<style name="AppTheme" parent="@style/Theme.AppCompat.Light" />

=====================================================================

引用主题属性:

5、“?”表示引用主题属性

引用当前主题中定义的属性。“@”表示引用具体的资源,而“?”表示当前theme中定义的属性,该属性指定了具体的资源值,实现了根据使用的不同theme使用不同的资源的功能。

例如:background="?colorPrimary"。在使用theme_white和theme_black时background的值分别是white和black

<style name="theme_white"parent="android:Theme.Holo.Light">

<itemname="android:colorPrimary">@android:color/white</item>

</style>

<style name="theme_black"parent="android:Theme.Holo.Light">

<itemname="android:colorPrimary">@android:color/black</item>

</style>

引用属性写法:

引用自定义属性:?attr/colorPrimary 简写:?colorPrimary

引用系统属性:?android:attr/colorPrimary 简写:?android:colorPrimary

其中,自定义属性会复写系统属性

引用属性时,不需要指定类型(?name == ?attr/name)

当colors.xml中有定义colorPrimary属性时,

鼠标在该属性上时“?colorPrimary”和“?attr/colorPrimary”均显示:

?attr/colorPrimary => @color/colorPrimary =>#3F51B5

所以:“?colorPrimary”只是“?attr/colorPrimary”的简写

鼠标在该属性上时“?android:colorPrimary”和“?android:attr/colorPrimary”均显示:

?android:attr/colorPrimary => ?attr/colorPrimary=> @color/colorPrimary => #3F51B5

所以:“?android:colorPrimary”只是“?android:attr/colorPrimary”的简写

当colors.xml中没定义colorPrimary属性时,

?attr/colorPrimary => @color/primary_material_light=> @color/material_grey_100 => #fff5f5f5

这是AppCompat包中定义的属性值

引用资源时,一定要指定类型(@name != @color/name)

@name会引用失败

因为不同类型的资源可以有相同的名称,如:R.color.white、R.style.white。

而主题属性不可以,并且在attrs.xml中就约束了其类型,所以属性引用可以省略,而资源引用不可以