Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Make "shrinkResources true" to keep all drawables, but remove other unused resources

I have a project which contains a lot of drawables, which are named starting with "a" or "b" (For example a1_back, a2_back, b1_start, b2_start and many-many more). Those drawables are not used in code, but used by the following code:

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

So, nowhere in code do I have specific string "a1_back" used. That's why when I set "shrinkResources true" all my drawables starting with "a" and "b" are removed.

I've read that you can specify what resources to keep using 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 way to many drawables and don't want to specify each one separately. Is there a way to set a pattern in "tools:keep"(to keep all drawables starting with "a" or "b") or maybe make it keep all drawables in project, but remove other unused resources?

Thanks in advance! :)

like image 356
hkop Avatar asked Dec 22 '16 10:12

hkop


People also ask

How do I get rid of unused resources?

In Android Studio Menu > Refactor > Remove Unused Resources... Select the resources you want to remove. You can exclude resources you want to keep by right-clicking on the resource item. Use Do Refactor to remove all Resources at once.

Does ProGuard remove unused resources?

Customize which code to keep For most situations, the default ProGuard rules file ( proguard-android- optimize.txt ) is sufficient for R8 to remove only the unused code. However, some situations are difficult for R8 to analyze correctly and it might remove code your app actually needs.


1 Answers

When accessing resource dynamically , use this trick as explained in Android User Guide using this example

String name = String.format("img_%1d", angle + 1);
res = getResources().getIdentifier(name, "drawable", getPackageName());
like image 188
Mohamed ALOUANE Avatar answered Sep 25 '22 09:09

Mohamed ALOUANE