Add drawable caching
Change-Id: I4de4b55c1eddfd43e53ead27e2a284a4c18cb3cb
(cherry picked from commit b0ee962da6fe994db45e2a8221896ab67c2604be)
diff --git a/bridge/src/android/content/res/Resources_Delegate.java b/bridge/src/android/content/res/Resources_Delegate.java
index ea320c7..c3d4cef 100644
--- a/bridge/src/android/content/res/Resources_Delegate.java
+++ b/bridge/src/android/content/res/Resources_Delegate.java
@@ -45,6 +45,7 @@
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
+import android.util.LruCache;
import android.util.TypedValue;
import android.view.ViewGroup.LayoutParams;
@@ -58,6 +59,9 @@
public class Resources_Delegate {
private static boolean[] mPlatformResourceFlag = new boolean[1];
+ // TODO: This cache is cleared every time a render session is disposed. Look into making this
+ // more long lived.
+ private static LruCache<String, Drawable.ConstantState> sDrawableCache = new LruCache<>(50);
public static Resources initSystem(BridgeContext context,
AssetManager assets,
@@ -75,6 +79,7 @@
* would prevent us from unloading the library.
*/
public static void disposeSystem() {
+ sDrawableCache.evictAll();
Resources.mSystem.mContext = null;
Resources.mSystem.mLayoutlibCallback = null;
Resources.mSystem = null;
@@ -137,9 +142,23 @@
@LayoutlibDelegate
static Drawable getDrawable(Resources resources, int id, Theme theme) {
Pair<String, ResourceValue> value = getResourceValue(resources, id, mPlatformResourceFlag);
-
if (value != null) {
- return ResourceHelper.getDrawable(value.getSecond(), resources.mContext, theme);
+ String key = value.getSecond().getValue();
+
+ Drawable.ConstantState constantState = key != null ? sDrawableCache.get(key) : null;
+ Drawable drawable;
+ if (constantState != null) {
+ drawable = constantState.newDrawable(resources, theme);
+ } else {
+ drawable =
+ ResourceHelper.getDrawable(value.getSecond(), resources.mContext, theme);
+
+ if (key != null) {
+ sDrawableCache.put(key, drawable.getConstantState());
+ }
+ }
+
+ return drawable;
}
// id was not found or not resolved. Throw a NotFoundException.