I am trying to do a application-wide font change and creating a style file to do so. In this file (below) I just want to change typeface value of TextAppearance style of Android.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="NightRiderFont" parent="@android:style/TextAppearance">
<item name="android:typeface"> /***help need here***/ </item>
</style>
</resources>
However font is in "assets/fonts/". How can I access this font, so I can use that style as a theme to get rid of changing all TextViews by hand programatically.
As summary: How can I access 'a file from assets folder' in XML?
Soorya is right, but if you have to put the same font on many textViews, I recommend you to put that code inside a static method that return the Typeface wanted. It will reduce lines in your code. Or even better create a class that extends Application and make a GET method that return the Typeface. That method will be reachable from any Activity inside your application (without the need of using static variables or static methods).
Instead of assets folder, you can put the .ttf file on fonts folder. To use fonts support in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26+. Right click res folder, new -> Android resource directory-> select font -> Ok. put your "myfont.ttf" file in newly created font folder.
On res/values/styles.xml add,
On layout file add android:textAppearance="@style/customfontstyle",
Refer : https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml
I took droid kid's answer and made it work with ANY font, just by typing the font filename directly into the XML:
layout.xml
Fonts.java
values/attrs.xml
TextViewWithFont.java
You can use this library: https://github.com/chrisjenx/Calligraphy
You only have to add the font you want to use on your layout. Like this:
Edit 2:
Finally fonts are supported by xml (also backwards compatible via support library): https://developer.android.com/preview/features/fonts-in-xml.html
Edit:
I now use the Calligraphy library . It is the easiest way for custom fonts.
What can you do:
TextView
I found another way to do this.
You have to make your own
TextView
using this tutorialIt is not that difficult and after this you can just use that
TextView
with your own font.I don't know if anybody still watches this, but I thought it might help.
In my research, there is no way to add external font to the xml file. Only the 3 default font is available in xml
But you can use in java using this code.
Update:
Now I find a way to do this by creating a custom class extending the TextView and use that in the xml file.
and in xml
dont forget to add the schema in root of your xml
And create an
attrs.xml
file insidevalues
directory, which is holding our custom attribues:Update:
Application class will look like this