欢迎转载,但请务必在明确位置注明文章出处! http://johnnyshieh.github.io/android/2014/09/12/android-accessing-resources/
1. 引用自定义资源文件
- 在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
2. 引用系统资源文件
系统资源文件分为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中声明的资源是google不推荐使用的)
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
<?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 );
3. 引用主题属性
- 格式为:?[<package_name>:]<resource_type>/<resource_name>
例如:android:textColor=”?android:textDisabledColor”
Android中还可以引用当前theme中定义的属性值或者style,不需要<resource_type>( type = ?android:attr/textDisabledColor),它会在主题中被查找
留言列表