Explorar o código

Merge pull request #101 from teslacoil/typefacehelper

Fix memory leak for font assets
Aidan Follestad %!s(int64=10) %!d(string=hai) anos
pai
achega
aec5348c26

+ 2 - 2
library/src/main/java/com/afollestad/materialdialogs/MaterialDialog.java

@@ -102,10 +102,10 @@ public class MaterialDialog extends DialogBase implements View.OnClickListener,
 
         this.regularFont = builder.regularFont;
         if (this.regularFont == null)
-            this.regularFont = Typeface.createFromAsset(getContext().getResources().getAssets(), "fonts/Roboto-Regular.ttf");
+            this.regularFont = TypefaceHelper.get(getContext(), "Roboto-Regular");
         this.mediumFont = builder.mediumFont;
         if (this.mediumFont == null)
-            this.mediumFont = Typeface.createFromAsset(getContext().getResources().getAssets(), "fonts/Roboto-Medium.ttf");
+            this.mediumFont = TypefaceHelper.get(getContext(), "Roboto-Medium");
 
         mContext = builder.context;
         this.view = LayoutInflater.from(getContext()).inflate(R.layout.md_dialog, null);

+ 43 - 0
library/src/main/java/com/afollestad/materialdialogs/TypefaceHelper.java

@@ -0,0 +1,43 @@
+package com.afollestad.materialdialogs;
+
+import android.content.Context;
+import android.graphics.Typeface;
+import android.support.v4.util.SimpleArrayMap;
+
+/*
+    Each call to Typeface.createFromAsset will load a new instance of the typeface into memory,
+    and this memory is not consistently get garbage collected
+    http://code.google.com/p/android/issues/detail?id=9904
+    (It states released but even on Lollipop you can see the typefaces accumulate even after
+    multiple GC passes)
+
+    You can detect this by running:
+    adb shell dumpsys meminfo com.your.packagenage
+
+    You will see output like:
+
+     Asset Allocations
+        zip:/data/app/com.your.packagenage-1.apk:/assets/Roboto-Medium.ttf: 125K
+        zip:/data/app/com.your.packagenage-1.apk:/assets/Roboto-Medium.ttf: 125K
+        zip:/data/app/com.your.packagenage-1.apk:/assets/Roboto-Medium.ttf: 125K
+        zip:/data/app/com.your.packagenage-1.apk:/assets/Roboto-Regular.ttf: 123K
+        zip:/data/app/com.your.packagenage-1.apk:/assets/Roboto-Medium.ttf: 125K
+
+*/
+public class TypefaceHelper {
+
+    private static final SimpleArrayMap<String, Typeface> cache = new SimpleArrayMap<>();
+
+    public static Typeface get(Context c, String name) {
+        synchronized (cache) {
+            if (!cache.containsKey(name)) {
+                Typeface t = Typeface.createFromAsset(
+                        c.getAssets(), String.format("fonts/%s.ttf", name));
+                cache.put(name, t);
+                return t;
+            }
+            return cache.get(name);
+        }
+    }
+}
+