Android:使“shrinkResources为true”保留所有drawable,但删除其他未使用的资源

时间:2016-12-22 10:39:26

标签: android proguard android-resources shrinkresources

我有一个包含大量drawable的项目,这些项目以“a”或“b”开头(例如a1_back,a2_back,b1_start,b2_start以及更多)。这些drawable不在代码中使用,但由以下代码使用:

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

因此,在代码中没有使用特定的字符串“a1_back”。这就是为什么当我设置“ shrinkResources true ”时,所有以“a”和“b”开头的drawable都被删除了。

我已经读过你可以指定使用以下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" />

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

提前致谢! :)

2 个答案:

答案 0 :(得分:3)

动态访问资源时,请使用此示例,如Android User Guide中所述,使用此示例

String name = String.format("img_%1d", angle + 1);
res = getResources().getIdentifier(name, "drawable", getPackageName());

答案 1 :(得分:1)

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

@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);

资源收缩机制用&#34;前缀_&#34;分析所有drawables可以使用,它不会触摸这些文件。