Skip to content
This repository has been archived by the owner on Aug 8, 2023. It is now read-only.

Commit

Permalink
[android] provide default font list for pre lollipop
Browse files Browse the repository at this point in the history
  • Loading branch information
tobrun committed Aug 19, 2019
1 parent 1846c05 commit d5a76f8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package com.mapbox.mapboxsdk.utils;

import android.graphics.Typeface;

import android.os.Build;
import android.support.annotation.RequiresApi;
import com.mapbox.mapboxsdk.MapStrictMode;
import com.mapbox.mapboxsdk.log.Logger;

Expand All @@ -18,6 +19,14 @@
public class FontUtils {

private static final String TAG = "Mbgl-FontUtils";
private static final String TYPEFACE_FONTMAP_FIELD_NAME = "sSystemFontMap";
private static final List<String> DEFAULT_FONT_STACKS = new ArrayList<String>() {
{
add("sans-serif");
add("serif");
add("monospace");
}
};

private FontUtils() {
// no instance
Expand All @@ -34,7 +43,13 @@ public static String extractValidFont(String... fontNames) {
return null;
}

List<String> validFonts = getAvailableFonts();
List<String> validFonts;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
validFonts = getDeviceFonts();
} else {
validFonts = DEFAULT_FONT_STACKS;
}

for (String fontName : fontNames) {
if (validFonts.contains(fontName)) {
return fontName;
Expand All @@ -47,16 +62,18 @@ public static String extractValidFont(String... fontNames) {
return DEFAULT_FONT;
}

private static List<String> getAvailableFonts() {
@SuppressWarnings( {"JavaReflectionMemberAccess", "unchecked"})
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private static List<String> getDeviceFonts() {
List<String> fonts = new ArrayList<>();
try {
Typeface typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL);
Field f = Typeface.class.getDeclaredField("sSystemFontMap");
f.setAccessible(true);
Map<String, Typeface> fontMap = (Map<String, Typeface>) f.get(typeface);
Field field = Typeface.class.getDeclaredField(TYPEFACE_FONTMAP_FIELD_NAME);
field.setAccessible(true);
Map<String, Typeface> fontMap = (Map<String, Typeface>) field.get(typeface);
fonts.addAll(fontMap.keySet());
} catch (Exception exception) {
Logger.e(TAG,"Couldn't load fonts from Typeface", exception);
Logger.e(TAG, "Couldn't load fonts from Typeface", exception);
MapStrictMode.strictModeViolation("Couldn't load fonts from Typeface", exception);
}
return fonts;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package com.mapbox.mapboxsdk.utils;

import android.support.test.runner.AndroidJUnit4;

import com.mapbox.mapboxsdk.constants.MapboxConstants;

import org.junit.Test;
import org.junit.runner.RunWith;

Expand Down

0 comments on commit d5a76f8

Please sign in to comment.