Android 如何引用库工程Library的资源

时间:2022-08-30 08:46:00

一、如何在工程A中直接引用库工程B的资源

方法一:直接将工程B的资源拷贝到工程A中

方法二:在工程A的java 代码中引用B的资源R,注意R需要带上包名。例如:

imageView.setImage(com.B.pkgname.R.drawable.image);
方式三:在工程A的layout.xml文件中引用B的资源。

<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:src="@*com.B.pkgname:drawable/share_ding" />

二、Android xml资源文件中引用写法含义

1、@代表引用资源
  • 引用自定义资源格式:@[package:]type/name
  • 引用系统资源格式:@android:type/name

2、@*代表引用系统的非public资源。格式:@*android:type/name

  •   系统资源定义分public和非public。public的声明在:<sdk_path>\platforms\android-8\data\res\values\public.xml
  •   @*android:type/name:可以调用系统定义的所有资源
  •   @android:type/name:只能够调用publi属性的资源
3、?代表引用主题属性
  android:textColor="?android:textDisabledColor" 
这个属性值只能在style资源和XML属性中使用;通过它可以改变当前主题的UI元素的外观。注意,这和资源引用非常类似,除了我们使用一个"?"前缀代替了"@"。当你使用这个标记时,你就提供了属性资源的名称,它将会在主题theme中进行查找。其命名语法和"@"形式一致:?[namespace:]type/name,这里类型type可以省略。

三、关于public.xml的配置,google文档的说明

https://developer.android.com/studio/projects/android-library.html#PrivateResources 

Choose resources to make public

All resources in a library default to public. To make all resources implicitly private, you must define at least one specific attribute as public. Resources include all files in your project’s res/ directory, such as images. To prevent users of your library from accessing resources intended only for internal use, you should use this automatic private designation mechanism by declaring one or more public resources.

To declare a public resource, add a <public> declaration to your library’s public.xml file. If you haven’t added public resources before, you need to create the public.xml file in the res/values/ directory of your library.

The following example code creates two public string resources with the names mylib_app_name and mylib_public_string:

<resources>
   
<public name="mylib_app_name" type="string"/>
   
<public name="mylib_public_string" type="string"/>
</resources>

You should make public any resources that you want to remain visible to developers using your library. For example, although most of the resources in the v7 appcompat library are private, attributes controlling the Toolbar widget are public to support material design.

Implicitly making attributes private not only prevents users of your library from experiencing code completion suggestions from internal library resources but also allows you to rename or remove private resources without breaking clients of your library. Private resources are filtered out of code completion and the theme editor, and Lint warns you when you try to reference a private resource.