You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android如何将模块/库资源设为私有?按文档操作后仍可被访问

如何正确将Android库模块的资源设为私有?

已尝试的操作

我按照官方文档创建了common库模块,并尝试了多种配置方式:

配置res/values/public.xml的两种写法

写法一:

<resources>
   <public name="app_name" type="string"/>
</resources>

写法二:

<resources>
    <public/>
</resources>

res/values/strings.xml内容

<resources>
  <string name="app_name">app_name</string>
  <string name="app_name_2">app_name_2</string>
</resources>

在strings.xml中直接添加public标签的两种写法

写法一:

<resources>
  <public name="app_name" type="string"/>
   
  <string name="app_name">app_name</string>
  <string name="app_name_2">app_name_2</string>
</resources>

写法二:

<resources>
  <public />
  <string name="app_name">app_name</string>
  <string name="app_name_2">app_name_2</string>
</resources>

遇到的问题

app模块仍能访问本应私有资源:android.example.common.R.string.app_name_2


正确解决方案

核心配置步骤

  1. 创建并配置public.xml
    在库模块的res/values/目录下创建public.xml,仅声明需要对外暴露的资源,未声明的资源会自动设为私有:

    <resources>
        <public name="app_name" type="string" />
    </resources>
    
  2. 清理并重建项目
    执行Android Studio的Build > Clean Project,再执行Build > Rebuild Project。旧的R类缓存可能导致私有资源仍被可见,重建后会生成新的仅包含公开资源的R类。

额外检查项

  • 确认public.xml路径正确:必须位于res/values/目录下,不能放在其他values-*子目录中
  • 检查Android Gradle插件版本:确保使用3.0.0及以上的稳定版本,旧版本可能存在资源权限处理的bug
  • 避免在库模块的build.gradle中添加导致资源全部公开的自定义配置

内容的提问来源于stack exchange,提问作者Arman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:40:19