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

hko*_*kop 7 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());
Run Code Online (Sandbox Code Playgroud)

所以,在代码中没有使用特定的字符串"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" />
Run Code Online (Sandbox Code Playgroud)

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

提前致谢!:)

Ale*_*cev 3

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

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

窍门在这里

final String prefixName = String.format("prefix_%s", name);
Run Code Online (Sandbox Code Playgroud)

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