7

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

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

所以,我在代码中没有使用特定的字符串“a1_back”。这就是为什么当我设置“ shrinkResources 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" />

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

提前致谢!:)

4

2 回答 2

3

动态访问资源时,请按照Android 用户指南中的说明使用此技巧

String name = String.format("img_%1d", angle + 1);
res = getResources().getIdentifier(name, "drawable", getPackageName());
于 2017-06-15T13:50:33.200 回答
2

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

@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都可以使用,并且不会触及这些文件。

于 2017-05-23T08:34:07.213 回答