Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache typefaces #252

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String, WeakReference<Typeface>> FONT_CACHE = new HashMap<>();

public static Typeface get(String name, AssetManager assets) {
if (!FONT_CACHE.containsKey(name)) {
return createAndAddTypeFace(name, assets);
}

WeakReference<Typeface> 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;
}
}