Android xml 资源文件中 @、@android:、@*、?的含义和区别

引用自定义资源文件

  • 在 xml 中引用的格式为:@[<package_name>:]<resource_type>/<resource_name>

<package_name>: 资源文件所在的包名( layout文件和自定义其他resource文件在同一个包,所以可以省略)
<resource_type>:资源文件的类型
<resource_name>:资源文件的名称

例如: android:text=”@string/hello”

  • 在代码中引用的格式为:R.<resource_type>.<resource_name>,如:R.string.hello

引用系统资源文件

系统资源文件分为 pulbic 和非 public,public 的声明在:<sdk_path>/platforms/android-19/data/res/values/public.xml

  • 引用 public 资源文件

xml: @android:<resource_type>/<resource_name>
code: android.R.<resource_type>.<resource_name>

例如:android:drawable=”@android:drawable/dialog_frame”
getResources.getDrawable( android.R.drawable.dialog_frame );

  • 引用非 public 资源文件 (没在 public.xml 中声明的资源是 Android 不推荐使用的)

xml: @*android:<resource_type>/<resource_name>
code: com.android.internal.R.<resource_type>.<resource_name> (如果只是基于原生 Android 开发第三方应用会报错)

但是如果要在代码中引用系统非 public 资源,可以通过 XML 引用中转,例如,需要引用 mz_btn_list_attachment_delete 这个 drawable 资源
先在 res/drawable/ 下新建 mz_btn_list_attachment_delete.xml

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@*android:drawable/mz_btn_list_attachment_delete_pressed"/>
<item android:drawable="@*android:drawable/mz_btn_list_attachment_delete_normal"/>
</selector>

最后在代码中 getResources.getDrawable( R.drawable.mz_btn_list_attachment_delete );

引用主题属性

  • 格式为:?[<package_name>:]<resource_type>/<resource_name>

例如:android:textColor=”?android:textDisabledColor”

Android 中还可以引用当前主题中定义的属性值或者 style,不需要 <resource_type>( type = ?android:attr/textDisabledColor),它会在主题中被查找

参考文章:

END
Johnny Shieh wechat
我的公众号,不只有技术,还有咖啡和彩蛋!