美文网首页shmily-iOS/Mac
Android资源引用详解

Android资源引用详解

作者: developerChenxi | 来源:发表于2018-01-31 19:12 被阅读0次

布局文件中资源引用的写法多种多样,且看以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)

详细来讲:

  • 使用@ 是引用一个具体的值比如color, string, dimension 等等这些具体的某个值。不管activity是什么主题的,@引用的值都不会改变

    <?xml version="1.0" encoding="utf-8"?>  
    <resources>  
        <color name="colorPrimary">#3F51B5</color>
    </resources>
    
  • ? 是引用一个style attribute,其值取决于当前使用的主题。值为当前主题下定义的属性值:

    <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的背景色就是当前主题下定义的colorPrimary

语法

引用resources (@)

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

  • 包名:可省略,即这个资源所属的package,默认就是你app的包名,还有一个预留的包——android,使用系统发布的资源。
  • 资源类型:R的子集,即资源的类型(color, string, dimen等等)
  • 资源名:我们要引用的资源的名称

例如:

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

这两种写法是等效的:

  • package(可不写) = com.myapp
  • 资源类型 = color
  • 资源名 = colorPrimary
    那么使用系统预定义的资源就是:
<……
android:background="@android:color/holo_orange_dark"
……>

这个例子拆解开来就是:

  • package = 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
>

相关文章

网友评论

    本文标题:Android资源引用详解

    本文链接:https://www.haomeiwen.com/subject/zomlzxtx.html