Android:设置“shrinkResources true”以保留所有可绘制对象,但删除其他未使用的资源

2024-01-12

我有一个包含很多可绘制对象的项目,这些可绘制对象以“a”或“b”开头(例如a1_back、a2_back、b1_start、b2_start 等等)。这些可绘制对象不在代码中使用,但由以下代码使用:

String name = image.getName();//getName() returns for examle "a1_back"
res = getResources().getIdentifier(name, "drawable", getPackageName());

因此,代码中没有任何地方使用特定的字符串“a1_back”。这就是为什么当我设置“收缩资源 true“我所有以“a”和“b”开头的可绘制对象都被删除。

我读到您可以使用以下 xml 文件指定保留哪些资源:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:keep="@layout/l_used_c"
    tools:discard="@layout/unused2" />

但我有很多可绘制对象,并且不想单独指定每一个。有没有办法在“tools:keep”中设置模式(以保留所有以“a”或“b”开头的可绘制对象),或者使其保留项目中的所有可绘制对象,但删除其他未使用的资源?

提前致谢! :)


您可以使用一个解决方法。为所有要保留的可绘制对象添加前缀

@Nullable
private Drawable getDrawableByName(@NonNull final Context context, @NonNull final String name) {
    final String prefixName = String.format("prefix_%s", name);
    return getDrawable(context, prefixName);
}

@Nullable
protected Drawable getDrawable(@NonNull final Context context, @NonNull final String name) {
    final Resources resources = context.getResources();
    final int resourceId = resources.getIdentifier(name, "drawable", context.getPackageName());
    try {
        return resources.getDrawable(resourceId, context.getTheme());
    } catch (final Resources.NotFoundException exception) {
        return null;
    }
}

窍门在这里

final String prefixName = String.format("prefix_%s", name);

资源收缩机制分析所有带有“prefix_”的drawables都可以使用,并且不会触及这些文件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android:设置“shrinkResources true”以保留所有可绘制对象,但删除其他未使用的资源 的相关文章

随机推荐