I'm trying to define a GUI layout using XML files in Android. As far as I can find out, there is no way to specify that your widgets should use a custom font (e.g. one you've placed in assets/font/) in XML files and you can only use the system installed fonts.
I know that, in the Java code, I could change the font of each widget manually using unique IDs. Alternatively, I could iterate over all the widgets in Java to make this change, but this would probably be very slow.
What other options do I have? Is there any better ways to making widgets that have a custom look? I don't particularly want to have to manually change the font for every new widget I add.
I might have a simple answer for the question without extending the TextView and implementing a long code.
Code :
Place the custom font file in assets folder as usual and try this. It works for me. I just dont understand why peter has given such a huge code for this simple thing or he has given his answer in old version.
Old question, but I sure wish I read this answer here before I started my own search for a good solution. Calligraphy extends the
android:fontFamily
attribute to add support for custom fonts in your asset folder, like so:The only thing you have to do to activate it is attaching it to the Context of the Activity you're using:
You can also specify your own custom attribute to replace
android:fontFamily
It also works in themes, including the AppTheme.
Peter's answer is the best, but it can be improved by using the styles.xml from Android to customize your fonts for all textviews in your app.
My code is here
Fontinator is an Android-Library make it easy, to use custom Fonts. https://github.com/svendvd/Fontinator
You can make easily custom textview class :-
So what you need to do first, make
Custom textview
class which extended withAppCompatTextView
.Now , every time Custom text view call and we will get int value from attribute
int fontValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","Lato-Regular.ttf",-1)
.Or
We can also get getTypeface() from view which we set in our xml (
android:textStyle="bold|normal|italic"
). So do what ever you want to do.Now, we make
FontUtils
for set any .ttf font into our view.The only way to use custom fonts is through the source code.
Just remember that Android runs on devices with very limited resources and fonts might require a good amount of RAM. The built-in Droid fonts are specially made and, if you note, have many characters and decorations missing.