Android: make "shrinkResources true" to save all drawings, but delete other unused resources

I have a project that contains many drawings whose names begin with "a" or "b" (for example, a1_back, a2_back, b1_start, b2_start and many, many others). These drawings are not used in the code, but are used by the following code:

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

So, nowhere in the code is there a specific line "a1_back". So when I set " shrinkResources true ", all of my drawings starting with "a" and "b" are deleted.

I read that you can specify which resources should be used in the following XML file:

 <?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" /> 

But I have a way to many drawings and do not want to specify them separately. Is there a way to set the template to "tools: keep" (to save all the drawings starting with "a" or "b"), or maybe make it save all the drawings in the project, but delete other unused resources?

Thanks in advance!:)

+5
source share
2 answers

There is a workaround that you can use. Add a prefix for all the drawings you want to save.

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

Trick here

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

The resource reduction mechanism analyzes that all drawings with the prefix_ can be used and do not touch these files.

+1
source

When accessing a resource, dynamically use this trick, as described in the Android User Guide , using this example

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

Source: https://habr.com/ru/post/1261704/


All Articles