I have been trying to get custom fonts to work in my extension (building with RUSH), and have finally achieved it using this code I found in the pull requests for the app inventor sources:
public static Typeface getTypeFace(Form form, String fontFile) {
if (fontFile == null || fontFile.isEmpty()) {
return null;
}
Typeface typeface = null;
if (!fontFile.contains("/")) {
if (form instanceof ReplForm) {
if (Build.VERSION.SDK_INT > 28) {
File file = new File("/storage/emulated/0/Android/data/edu.mit.appinventor.aicompanion3/files/assets/" + fontFile);
typeface = Typeface.createFromFile(file);
} else {
File file = new File("/storage/emulated/0/AppInventor/assets/" + fontFile);
typeface = Typeface.createFromFile(file);
}
File file = new File("/storage/emulated/0/Android/data/edu.mit.appinventor.aicompanion3/files/assets/" + fontFile);
typeface = Typeface.createFromFile(file);
} else {
typeface = Typeface.createFromAsset(form.$context().getAssets(), fontFile);
}
}
return typeface;
}
However, @ewpatton suggested using the following code from the MediaUtil jar to avoid any hardcoding issues, however, the MediaUtil.fileUrlToFilePath
is private and cannot be accessed ?
Anyway I can use this second method ?
public static Typeface getTypeFace(Form form, String fontFile) {
if (fontFile == null || fontFile.isEmpty()) {
return null;
}
Typeface typeface = null;
File file;
if (!fontFile.contains("/")) {
if (form instanceof ReplForm) {
try {
file = new File(MediaUtil.fileUrlToFilePath(form.getAssetPath(fontFile)));
typeface = Typeface.createFromFile(file);
} catch (IOException ioe) {
}
} else {
typeface = Typeface.createFromAsset(form.$context().getAssets(), fontFile);
}
} else {
file = new File(fontFile);
typeface = Typeface.createFromFile(file);
}
return typeface;
}