react native custom fonts - android

This question has been already here and here, but the answer is not satisfactory there. The fonts are not working on android but on iOS do. Maybe I made some mistake during the linking.
How did I added fonts:
Created folder assets/fonts/ inside root folder.
Added
"rnpm": { "assets": ["./assets/fonts"] }
react-native link
Console output was it successfully added assets to iOS and Android
Added fontFamily: 'MyCustomFontFamily' into styles.
Run on iOS, everything worked fine.
Run on Android, no typeface.
Checked the android project directory and the assets folder was present
I tried adding (Platform.OS === 'ios') ? 'MyCustomFontFamily' : 'fonts/my_custom_font_family' to go with the file name but this did not work wither.
Tried same variation as 9 without path or with extension but no luck
Read here to use weight, tried it, no luck.

I had the same issue, which had to do with the fact that, as you already know, Android will read from the filename whilst iOS will read from the full name property. And, indeed, I had mixed up my fonts' references.
The first thing I did to solve this was to double-check that my fonts were properly located in android/app/src/main/assets/fonts/.
Then I ended up renaming my fonts to the exact same name as the one used by iOS and using that name as a reference. Here is what I mean:
export const sansSerifLight = 'Aileron-Light'; // Filename is 'Aileron-Light.otf'
export const sansSerifRegular = 'Aileron-Regular'; // Filename is 'Aileron-Regular.otf'
export const sansSerifBold = 'Aileron-Bold'; // Filename is 'Aileron-Bold.otf'
export const serifRegular = 'LibreBaskerville-Regular'; // Filename is 'LibreBaskerville-Regular.ttf'
export const serifBold = 'LibreBaskerville-Bold'; // Filename is 'LibreBaskerville-Bold.ttf'
export const serifItalic = 'LibreBaskerville-Italic'; // Filename is 'LibreBaskerville-Italic.ttf'
export const sansSerifTitle = 'ADAM.CG PRO'; // Filename is 'ADAM.CG PRO.otf'
export const serifTitle = 'Oranienbaum'; // Filename is 'Oranienbaum.ttf
And then :
<MyComponent style={{ fontFamily: serifTitle }} />
This really made things way less error-prone and easier to maintain for me.

Related

CapacitorJS: File selection issue with Input file on Android

I have an issue with file selection on Android by using input type file and capacitor-file-picker plugin. Same issue with both.
When I click on the Browse button, it takes me to the Recent files box. In the sidebar, when I choose Downloads or Documents, it displays files that are disabled.
But if I go to Gallery then I can select the photo and it works fine. It's the same for Audio files. I can select files and get a proper response.
What I'm trying to do is to select a single CSV file and get a response. No other files should be allowed to select. This is my code.
<template>
<input type="file" accept=".csv" #change="handleFileUpload($event)" />
<button fill class="my-3" #click="pickFile">Upload File</button>
</template>
<script setup>
import { FilePicker } from "#robingenz/capacitor-file-picker";
import { ref } from "vue";
const file = ref('');
const content = ref({});
const handleFileUpload = (event) => {
file.value = event.target.files[0];
console.log(file.value);
};
const pickFile = async () => {
const result = await FilePicker.pickFiles({
types: ["text/csv"],
});
if (result) {
content.value = result.files[0];
console.log(content.value);
}
};
</script>
I have tested this on Xiaomi 11T (MIUI v13.0.3, Android v12), OnePlus 5T (PixelExperience, Andoird v12) and Android Studio Emulator Pixel XL Android v11.
Everything works fine on the Windows Chrome browser.
I'm using Capacitor Filesystem plugin for a different purpose (downloading CSV file) and android.permission.READ_EXTERNAL_STORAGE and android.permission.WRITE_EXTERNAL_STORAGE is already set in AndroidManifest.xml.
What am I doing wrong? Any help would be appreciated.
Thanks
type text/comma-separated-values instead of text/csv fixed this issue as suggested by Robin Genz on Github issue for capacitor-file-picker plugin. It's the same for input type="file".
<input type="file" accept="text/comma-separated-values" #change="fileUpload($event)" />

Android react-native app not picking up font

I am trying to use a font "Verveine Corp Regular' inside my react-native app.
The font works in the iOS build, but not in the Android build.
The font is in .tff format and is placed in the root of my work (linked in the package.json and I have run react-native link) and inside "android/gradle/src/main/assets/fonts" but it's still not picking the font up. I have also cleaned and rebuilt the app multiple times.
When inspecting an element which uses the font in the android debugger, it says it's using the font. But the font is still the default font.
Could anyone offer some help or guidance on this issue?
Thanks!
The other answers helped me get this working for me, thank you. This manuever is probably only necessary when the font has capital letters in the filename. A more complete answer:
Add the font as normal in react native, for example:
{react-native-project}/fonts/GovtAgentBB.ttf
Run react-native link and this will put the font in
{react-native-project}/android/app/src/main/assets/fonts/GovtAgentBB.ttf
{react-native-project}/android/app/src/main/assets/fonts/GovtAgentBB_ital.ttf
But android, bring robotic and not human, doesn't like this. So rename the file with all lower case letters and an underscore before the variant, like:
{react-native-project}/android/app/src/main/assets/fonts/govtagentbb.ttf
{react-native-project}/android/app/src/main/assets/fonts/govtagentbb_ital.ttf
Then, you have to change the font name in the style depending on the platform. For iOS, use the human name that is the name of the font that would be displaying in the title of the window of the Mac Font menu (or just the name you see on the web). For android, you have to, robotically, use the name of the file you just renamed.
{Platform.OS === 'ios' ? (
<Text style={styles.welcome}>
Hello World!
</Text>
) : (
<Text style={styles.welcomeAndroid}>
Hello World
</Text>
)}
const styles = StyleSheet.create({
...
welcome: {
fontFamily: 'Government Agent BB',
},
welcomeAndroid: {
fontFamily: 'govtagentbb',
},
This is how I used custom font in my project
//sampleStyle.js
import overrideStyles from '/sampleoverridestyles';
iconTextStyle: {
color: '#FFFFFF',
fontSize: 16
}
//sampleoverridestyles.ios.js
export default {
iconTextStyle: {
fontFamily: 'FaktSoftPro-Medium'
}
}
//sampleoverridestyles.android.js
export default {
iconTextStyle: {
fontFamily: 'faktsoftpro_medium'
}
}
since I cannot set the font name same for iOS and android I have overridden it as above and it worked.
Guys if you are following all other solution and still no update then try following the steps
add react-native-config.js file
then add fonts in assets/fonts/your font
rename it with lowercase like OpenSans_Regular to opensans_regular
react-native link in terminal in your project folder
after all build your project again using react-native run-android
fontFamily: Platform.OS === "ios" ? 'opensans_regular' : 'cassandrapersonaluseregular_3bjg',
I was also getting the same issue the font was not reflecting changes then I build my project again that was my mistake because we adding fonts in our android folder so we need to compile that again.
I hope someone may save their time
I added font in react-native android from here:
https://medium.com/#gattermeier/custom-fonts-in-react-native-for-android-b8a331a7d2a7#.40vw3ooar
Follow all the steps it will work fine.
After adding run react-native run-android
First, make sure you are up to version 0.16+ with react-native.
Your fonts should be *.ttf or *.otf files and must be located in: /projectname/android/app/src/main/assets/fonts
Make sure the fonts are lowercase only and follow this pattern: fontname.ttf, fontname_bold.ttf, fontname_light.ttf, fontname_bold_italic.ttf
Have you defined another font in your AppTheme (styles.xml), that overrides your preferred font?
Have you tested your font with a "Hello World"-App as a minimal test?
Have you implemented your ttf as shown here for example?: How to use custom font in Android Studio

Global Variable / Constant in React Native

is there a way in React Native that I can define on a global variable all the strings that I will be using like in Android Development there is a String.xml where you can put all of your strings.
What' I've done is create a globals module...
// File: Globals.js
module.exports = {
STORE_KEY: 'a56z0fzrNpl^2',
BASE_URL: 'http://someurl.com',
COLOR: {
ORANGE: '#C50',
DARKBLUE: '#0F3274',
LIGHTBLUE: '#6EA8DA',
DARKGRAY: '#999',
},
};
Then I just require it at the top...
const GLOBAL = require('../Globals');
And access them like so...
GLOBAL.COLOR.ORANGE
_____________________
UPDATE on Feb 10, 2018
This seems to be a pretty popular and useful answer, so I thought I should update it with the more current syntax. The above still works in CommonJS module systems, but now days you're just as likely to run into ES6 and importmodules rather than require them.
ECMAScript Modules (ESM) Syntax
// File: Globals.js
export default {
STORE_KEY: 'a56z0fzrNpl^2',
BASE_URL: 'http://someurl.com',
COLOR: {
ORANGE: '#C50',
DARKBLUE: '#0F3274',
LIGHTBLUE: '#6EA8DA',
DARKGRAY: '#999',
},
};
// to use...
import GLOBALS from '../Globals'; // the variable name is arbitrary since it's exported as default
// and access them the same way as before
GLOBALS.COLOR.ORANGE
global in react native is like the window in web development.
// declare a global varible
global.primaryColor = '***';
//now you can use this variable anywhere
console.log(primaryColor);
I too made a module like in Chris Geirman's answer, but was not able to reference it with the require. Instead I got it to work with import * as GLOBAL from '../Globals';
If you want to switch between languages depening on platform localisation.
fetch node_module via npm
npm i react-native-localization --save
Define variables in class:
// Localisation.js
let LocalizedStrings = require ('react-native-localization');
let strings = new LocalizedStrings ({
en: {
loginTitle: "Login",
},
de: {
loginTitle: "Anmelden",
}
})
When you need the strings:
var STRINGS = require ('./Localization');
<Text>{STRINGS.loginTitle}</Text>

react-native android fontFamily does not take effect

Question 1:
I add a fontFamily to index.android.js's welcome style, but it takes no effect. Does fontFamily actually work on android?
welcome:{
fontSize:20,
fontFamily:'roboto-thin',
textAlign:'center',
margin:10}
Question 2:
if fontFamily works on android, is there a way to load custom font from assets? Or is this some feature to be implemented by react-native?
For Android:
Custom fonts were added with 0.16.0-rc. So you need to have 0.16.0-rc version first and after that you can just download any fonts from the web.
Put your font files in projectfolder/android/app/src/main/assets/fonts/font_name.ttf
Remember to recompile which is: react-native run-android
And then you can use fontFamily: 'font_name' in your style.
Also note the following restrictions for custom Android fonts in react-native:
fonts must be placed in android/app/src/main/assets/fonts
only .ttf files are supported
The name of the file has to match the fontFamily exactly. For instance, if fontFamily is 'Source Sans Pro',
the file must be called Source Sans Pro.ttf (and NOT SourceSansPro.ttf). Any suffixes as mentioned in the following paragraph are automatically removed from the file.
When the font is in bold and/or italic, it must use on the following suffixes:
_bold (e.g. Source Sans Pro_bold.ttf)
_italic
_bold_italic
Hello this issue waist for me more than two days with "El+Messiri" font "https://fonts.google.com/specimen/El+Messiri"
i was doing every think write :
Put your font files in
projectfolder/android/app/src/main/assets/fonts/ElMessiri-Regular.ttf
Remember to recompile which is: react-native run-android And then
you can use fontFamily: 'ElMessiri-Regular' in your style.
but the fault was that am using fontWeight : 'bold' after fontFamily: 'ElMessiri-Regular' and the fontWeight was overiding the fontFamily because "El+Messiri" font has his own fontFamily bold wich is "ElMessiri-Bold"
I believe the following is a cleaner alternative to the methods already explained here:
Put all your fonts in you React-Native project directory
./assets/fonts/
Add the following line in your package.json
"rnpm": {
"assets": ["./assets/fonts"]
}
finally run in the terminal from your project directory
$ react-native link
to use it declare this way in your styles
fontFamily: 'your-font-name without extension'
If your font is Raleway-Bold.ttf then,
fontFamily: 'Raleway-Bold'
Source https://medium.com/#danielskripnik/how-to-add-and-remove-custom-fonts-in-react-native-b2830084b0e4
This feature has yet to be implemented. See the relevant issue on github here.
It seems like custom font was added, check out this commit:
https://github.com/facebook/react-native/commit/bfeaa6a4f531cfc18c097bc9ffb6a8dbe3ddc702
For those facing problems with iOS only - which sometimes does not recognize the fontFamily name correctly:
The only solution that solved my problem was to log all the fonts to find out correct naming
(make sure you do the steps below only after adding the assets/fonts and running the react-native link):
Anyway, to log them, open the appName.xcworkspace file with xcode and then edit AppDelegate.m putting this lines at the end of the didFinishLaunchingWithOptions method (and before the return statement):
for (NSString* family in [UIFont familyNames])
{
NSLog(#"%#", family);
for (NSString* name in [UIFont fontNamesForFamilyName: family])
{
NSLog(#" %#", name);
}
}
So, when you run the app (from xcode) it outputs something like this:
This way, I can use the fontFamily Barow-Light or Zapfino inside my react-native styles
Hope it helped!
I had an incredibly hard time with this, even after following all advice I found.
What worked for me: ensure the font file is named using only lowercase letters and underscores. Re-link. Done.
A lot of hair pulling has been done over this yet it isn't mentioned anywhere as far as I can see.

FLEX Android: Do I need to copy .db and .xml to ApplicationStorage manually?

On flex app for Android first start (or after deleting app data), does Flex handle copying assets files from assets/ folder to File.applicationStorageDirectory, or is developer responsible for checking whether file exists there, and if not, copying ones from assets/ to File.applicationStorageDirectory?
If this goes by unanswered, I don't mind investigating it further and answering it myself, I was just wondering if someone knows this by heart.
Thanks!
Do you use Flash Builder?
In its menu there is Project -> Export Release Build... -> Next -> Package Contents and you can add your assets by toggling checkboxes.
Ok, here goes:
Flex does not take care of that - we have to do it manually.
I will use the following code to make sure my file exists in ApplicationStorageDirectory:
import flash.filesystem.File;
public const FNAME:String = "myDBFileName.db";
private var dbFile:File = File.applicationStorageDirectory.resolvePath(FNAME);
// 'original', initial file
private var originalDB:File =File.applicationDirectory.resolvePath(FNAME);
public function MyOpenFile(){
if (!dbFile.exists){
// It does not exist in AppStorageDirectory, so copy it from app instalation directory
originalDB.copyTo(dbFile);
}
// from here on, we can safely use dbFile.
}
So on 1st launch (and after 'delete app data'), app will copy original file to ApplicationStorageDirectory, and continue using it from there.

Categories

Resources