Skip to content

Commit

Permalink
Feat: Allow using custom font on android (#487)
Browse files Browse the repository at this point in the history
* feat: allow using custom font on android

* fix: fallback when a font file doesn't exist

---------

Co-authored-by: camilossantos2809 <camilossantos2809@github.com>
  • Loading branch information
camilossantos2809 and camilossantos2809 authored Dec 15, 2023
1 parent 46ce1c3 commit 667c47d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}
}
}

Expand Down
2 changes: 2 additions & 0 deletions typings/Picker.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export interface PickerItemProps<T = ItemValue> {
* - 'backgroundColor'
* - 'fontSize'
* - 'fontFamily'
*
* The 'fontFamily' value expects the font file (.ttf) to be present in the "assets/fonts" directory
*
* @platform android
*/
Expand Down

0 comments on commit 667c47d

Please sign in to comment.