How to set custom font in .xml file instead of .java file?
For your reference,
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
public void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/yourfont.ttf");
setTypeface(tf ,1);
}
}
In XML,
<you_package.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Your text"
/>
How to use custom font in android xml?
The best way i found by googling is- Say if you want to use in TextView then we have to extend the Textview and have to set the font in that later we can use our customised Textview in our xml. I'll show the extended TextView below
package com.vins.test;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"your_font.ttf");
setTypeface(tf);
}
}
We calling init() to set font in each of the costructors.
Later we have to use this in our main.xml as shown below.
<com.vins.test.MyTextView
android:id="@+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1"
android:text="This is a text view with the font u had set in MyTextView class "
android:textSize="30dip"
android:textColor="#ff0000"
>
Update:
Be aware about the memory leak in pre-4.0 Android as mentioned by pandre.
Using a custom typeface in Android
Is there a way to do this from the
XML?
No, sorry. You can only specify the built-in typefaces through XML.
Is there a way to do it from code in
one place, to say that the whole
application and all the components
should use the custom typeface instead
of the default one?
Not that I am aware of.
There are a variety of options for these nowadays:
Font resources and backports in the Android SDK, if you are using
appcompat
Third-party libraries for those not using
appcompat
, though not all will support defining the font in layout resources
How to use custom font in a project written in Android Studio
Update 2021:
Create a folder named font inside the res folder and copy your font
All font names must be only: lowercase a-z, 0-9, or underscore.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/abc_font" />
For programmatic use:
textView.setTypeface(ResourcesCompat.getFont(context, R.font.abc_font))
For Android Studio 4.2+ there's even now a menu option:
custom fonts in android project
You unfortunately cannot. You can do that programmatically only, as android does not have built-in support for that through XML.
Showing custom font or View in preview section of Android Studio XML
To make FontAwesome icons visible in Android Studio XML designer you can.
- Create custom view
- Apply font in constructor
- Add custom attr if you want to set font from xml
Here is full demo code in gist
Demo img with code from comment:
Important parts: (pretty much the same as Declaring a custom android UI element using XML but with small tuning)
TextViewWithFont.java - Custom view class
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.TextView;
public class TextViewWithFont extends TextView {
public TextViewWithFont(Context context) {
super(context);
init(context, null, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
// Load attributes
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextViewPlusFont, 0, 0);
try {
String fontInAssets = ta.getString(R.styleable.TextViewPlusFont_customFont);
setTypeface(Typefaces.get(context, "fonts/"+ fontInAssets));
} finally {
ta.recycle();
}
}
}
res/values/attrs.xml - Need this to use app:customFont="fontawesome-webfont.ttf"
in our layout xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewPlusFont">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
Typefaces.java - Helper class to reuse fonts (Cache for fonts)
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.util.Hashtable;
public class Typefaces {
private static final String TAG = "Typefaces";
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public static Typeface get(Context c, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface t = Typeface.createFromAsset(c.getAssets(),
assetPath);
cache.put(assetPath, t);
Log.e(TAG, "Loaded '" + assetPath);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface '" + assetPath
+ "' because " + e.getMessage());
return null;
}
}
return cache.get(assetPath);
}
}
}
activity_main.xml - Layout and how to use TextViewWithFont custom view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<com.example.TextViewWithFont
xmlns:app="http://schemas.android.com/apk/res/com.example"
app:customFont="fontawesome-webfont.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="\uf1e2"
android:textSize="60dp"/>
</LinearLayout>
Related Topics
What Is the Recommended Way to Escape HTML Symbols in Plain Java
Why Doesn't Recyclerview Have Onitemclicklistener()
Noclassdeffounderror - Eclipse and Android
How to Create Android Facebook Key Hash
Rjava Load Error in Rstudio/R After "Upgrading" to Osx Yosemite
Solving a "Communications Link Failure" With Jdbc and MySQL
Error Java.Lang.Outofmemoryerror: Gc Overhead Limit Exceeded
How Does Java Handle Integer Underflows and Overflows and How Would You Check For It
:: (Double Colon) Operator in Java 8
How to Efficiently Parse HTML With Java
How to Write Files to External Public Storage in Android So That They Are Visible from Windows
Fast Bitmap Blur For Android Sdk
How to Implement Custom Action Bar With Custom Buttons in Android
Sort Arraylist of Custom Objects by Property
Convert a String Representation of a Hex Dump to a Byte Array Using Java