From 667c47d252ae46b3967281238c4d481deb8fb9e5 Mon Sep 17 00:00:00 2001 From: Camilo Santos Date: Fri, 15 Dec 2023 04:20:02 -0300 Subject: [PATCH] Feat: Allow using custom font on android (#487) * feat: allow using custom font on android * fix: fallback when a font file doesn't exist --------- Co-authored-by: camilossantos2809 --- .../picker/ReactPickerManager.java | 17 +++++++++++++---- typings/Picker.d.ts | 2 ++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/android/src/main/java/com/reactnativecommunity/picker/ReactPickerManager.java b/android/src/main/java/com/reactnativecommunity/picker/ReactPickerManager.java index 22334aa221..6299432d9f 100644 --- a/android/src/main/java/com/reactnativecommunity/picker/ReactPickerManager.java +++ b/android/src/main/java/com/reactnativecommunity/picker/ReactPickerManager.java @@ -8,6 +8,7 @@ package com.reactnativecommunity.picker; import android.content.Context; +import android.content.res.AssetManager; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; @@ -30,12 +31,12 @@ import com.facebook.react.uimanager.*; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.events.EventDispatcher; - import com.facebook.yoga.YogaMeasureFunction; import com.facebook.yoga.YogaMeasureMode; import com.facebook.yoga.YogaMeasureOutput; import com.facebook.yoga.YogaNode; +import java.io.IOException; import java.util.Map; import javax.annotation.Nullable; @@ -373,10 +374,18 @@ private View getView(int position, View convertView, ViewGroup parent, boolean i if (style.hasKey("fontSize") && !style.isNull("fontSize") && style.getDouble("fontSize") > 0.1) { textView.setTextSize((float)style.getDouble("fontSize")); } - + if (style.hasKey("fontFamily") && !style.isNull("fontFamily") && style.getString("fontFamily").length() > 0) { - Typeface face = Typeface.create(style.getString("fontFamily"), Typeface.NORMAL); - textView.setTypeface(face); + String fontPath = "fonts/" + style.getString("fontFamily") + ".ttf"; + AssetManager assetManager = convertView.getContext().getAssets(); + try { + assetManager.open(fontPath); + Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(), fontPath); + textView.setTypeface(face); + } catch (IOException e) { + Typeface face = Typeface.create(style.getString("fontFamily"), Typeface.NORMAL); + textView.setTypeface(face); + } } } diff --git a/typings/Picker.d.ts b/typings/Picker.d.ts index 5ebb2d36a6..67a1e4b60f 100644 --- a/typings/Picker.d.ts +++ b/typings/Picker.d.ts @@ -24,6 +24,8 @@ export interface PickerItemProps { * - 'backgroundColor' * - 'fontSize' * - 'fontFamily' + * + * The 'fontFamily' value expects the font file (.ttf) to be present in the "assets/fonts" directory * * @platform android */