shmily-iOS/Mac

Android资源引用详解

2018-01-31  本文已影响0人  developerChenxi

布局文件中资源引用的写法多种多样,且看以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。。。。那么接下来就详细说说,这些都代表了什么

理解 @ 和 ?

首先我们需要理解@和?分别引用的是什么内容

@ :引用资源(resources)
? :引用样式属性(style attribute)

详细来讲:

语法

引用resources (@)

@[包名:]资源类型/资源名

例如:

<……
android:background="@color/colorPrimary"  
android:background="@com.myapp:color/colorPrimary"
……>

这两种写法是等效的:

<……
android:background="@android:color/holo_orange_dark"
……>

这个例子拆解开来就是:

PS:
使用AppCompat定义的资源的资源时,常见以下的写法:
android:background="?selectableItemBackground"
我们并没有定义这些资源,也没有使用预留包名,之所以能这样使用是因为AppCompat那些资源被整合到了app中,不需要使用android关键字来引用。

引用样式属性(?)

语法与@相似

?[包名:][资源类型/]资源名称
区别在于,资源类型也是可不写的,因为这里唯一允许的资源类型是attr。
下面的表述方式其实完全是一样的:

<
android:background="?com.demo.app:attr/colorPrimary" //完整写法  
android:background="?com.demo.app:colorPrimary" //省略attr
android:background="?attr/colorPrimary" //省略包名  
android:background="?colorPrimary"  // 省略包名和 attr
>
上一篇 下一篇

猜你喜欢

热点阅读