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

Android资源压缩时如何保留外部库的refs.xml并使其生效?

解决Android库中refs.xml在资源压缩时失效的问题

问题背景

开发的Android库通过values/refs.xml使用tools:override属性覆盖Material组件的对话框按钮布局,代码如下:

<resources xmlns:tools="http://schemas.android.com/tools">
    <item name="mtrl_alert_dialog_actions" type="layout" tools:override="true">@layout/mtrl_alert_dialog_actions_custom</item>
</resources>

Debug模式下未启用资源压缩时功能正常,但主应用开启shrinkResources后,库中的refs.xml失效;将该文件移入主应用则可正常覆盖,需实现无需移动文件、库中refs.xml在资源压缩时仍生效的效果,且构建输出未提及库中refs.xml被移除。

解决方案

1. 给库添加资源保留配置文件

在库的res/raw目录下创建keep.xml(无raw目录则新建),内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:keep="@layout/mtrl_alert_dialog_actions_custom, @item/mtrl_alert_dialog_actions" />

这个文件会告知资源压缩工具,必须保留指定的自定义布局和资源覆盖条目,避免被误判为未使用资源移除。

2. 通过Gradle构建脚本强制保留资源

若使用Android Gradle Plugin 7.0及以上版本,可直接在库的build.gradle中配置资源使用规则:

android {
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true

            resourceUsageRules {
                keep {
                    resources = ['@layout/mtrl_alert_dialog_actions_custom', '@item/mtrl_alert_dialog_actions']
                }
            }
        }
    }
}

这种方式无需额外创建文件,直接通过构建脚本指定需保留的资源,确保资源压缩时不会处理这些关键内容。

3. 检查依赖配置

确保主应用以implementation或api方式引入该库,保证库的资源能被正确合并到主应用的资源集中。

原因分析

主应用开启shrinkResources后,资源压缩工具会扫描所有资源并移除未被直接引用的内容。库中的refs.xml用于覆盖系统资源,但主应用并未直接引用库内的mtrl_alert_dialog_actions_custom布局或refs.xml中的条目,导致这些资源被误判为未使用而移除,最终覆盖逻辑失效。通过添加保留规则,可强制工具保留这些关键资源,使覆盖功能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:55:17