diff --git a/library/src/main/java/com/rengwuxian/materialedittext/MaterialEditText.java b/library/src/main/java/com/rengwuxian/materialedittext/MaterialEditText.java index 06a8bf6f..21fb955b 100644 --- a/library/src/main/java/com/rengwuxian/materialedittext/MaterialEditText.java +++ b/library/src/main/java/com/rengwuxian/materialedittext/MaterialEditText.java @@ -485,7 +485,7 @@ public void afterTextChanged(Editable s) { } private Typeface getCustomTypeface(@NonNull String fontPath) { - return Typeface.createFromAsset(getContext().getAssets(), fontPath); + return TypefaceCache.get(fontPath, getContext().getAssets()); } public void setIconLeft(@DrawableRes int res) { diff --git a/library/src/main/java/com/rengwuxian/materialedittext/TypefaceCache.java b/library/src/main/java/com/rengwuxian/materialedittext/TypefaceCache.java new file mode 100644 index 00000000..e61fc2aa --- /dev/null +++ b/library/src/main/java/com/rengwuxian/materialedittext/TypefaceCache.java @@ -0,0 +1,35 @@ +package com.rengwuxian.materialedittext; + +import android.content.res.AssetManager; +import android.graphics.Typeface; + +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.Map; + +public class TypefaceCache { + private static final Map> FONT_CACHE = new HashMap<>(); + + public static Typeface get(String name, AssetManager assets) { + if (!FONT_CACHE.containsKey(name)) { + return createAndAddTypeFace(name, assets); + } + + WeakReference reference = FONT_CACHE.get(name); + Typeface typeFace = reference.get(); + + if (typeFace != null) { + return typeFace; + } + + return createAndAddTypeFace(name, assets); + } + + private static Typeface createAndAddTypeFace(String name, AssetManager assets) { + Typeface typeface = Typeface.createFromAsset(assets, name); + + FONT_CACHE.put(name, new WeakReference<>(typeface)); + + return typeface; + } +}