ChatGPT解决这个技术问题 Extra ChatGPT

Can I embed a custom font in an Android application?

I would like to have an app include a custom font for rendering text, load it, and then use it with standard elements like StaticText. Is this possible?


j
joar

Yes you can, you jsut can't define it into xml layouts. You need to use it dynamically each time. Check this tutorial for instance.

In case link is dead, here is a sum up of the stuff :

Get a font file like times.otf

Drop it in your asset folder, inside a "fonts" folder

Get a reference of TextView with something like that: TextView tv = (TextView) findViewById(R.id.myCustomTVFont);

Grab you font from the asset folder: Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/times.otf");

Make your TextView look great: tv.setTypeface(tf);


Hope the tutorial won't disappear one day.
As Martin rightly pointed it out, this needs a little edit, in case the link died out.
This tutorial did helped me. This is an ultimate solution to my problem :)
Tried it on a API 2.1 device. Didn't work good. I guess maybe my font was big and caused memory issues. Or similar. I just found something that may be a fix: stackoverflow.com/a/5941665/129202
A copy of the original tutorial: web.archive.org/web/20140115015420/http://…
M
Matt

As of Android 8.0 (API level 26), you can use fonts in XML. See the documentation here.


C
Community

Your can take look in this thread as well to set custom fonts for all the views in your activity.


As in the other answer to this question, it would be really handy if the important content of the thread was inside the question, in case the link dies one day.