简体   繁体   中英

I can't apply Typeface programmatically for Google font in Android Studio

I added a Google font using Android Studio,
It created a 'font' folder and under it is an XML file as follow:

res -> font -> font_name.xml

I'm trying to apply it programmatically but I can'y find how to do it,
I've tried several codes but nothing worked, examples:

Typeface font = Typeface.createFromFile("font/font_name.xml");

or

Typeface font = Typeface.createFromAsset(getAssets(), "@font/font_name");

Please note,
The 'font' folder along with the 'font_name.xml' file,
Were created automatically by Android Studio.

Your help would be appreciated,
Thank you.

I am certainly not an expert, but I managed to get my Typefaces working. Firstly, this thread contains a lot of useful info: Custom fonts and XML layouts (Android)

Now specifically to your problem, the way I managed to get Typefaces to work is by downloading a .ttf file either somewhere online, or when using android studio and clicking more fonts, set the radio button to add font to project. That will download the .ttf to res\\font\\font.ttf Move it to your assets directory into fonts folder and then create the typeface like this:

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/font.ttf");

If you want to use your font often and don't want to bother setting it every time, a good idea might be extending a TextView or whatever class you need and using the .setTypeface() method in the custom constructor.

Just solved this myself, here is what I have put together.

 Typeface font = Typeface.create("cursive", Typeface.NORMAL);
 Log.e("Setup",  "Font: " + font.getStyle());
 signatureButton.setTypeface(font);

The log just checks if you have selected an acceptable font, it should return 0 if not. The hardest part was finding a font family that worked. The key is to go to your XML file and type "android:fontFamily=" from here a suggestion list should pop up with choices at the bottom.

To change the google font family

 Typeface typeface = ResourcesCompat.getFont(this, R.font.your_font);
 textView.setTypeface(typeface); 

Add that to your fonts folder then use them in the XML or programmatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM