how can i set a font, whose ttf resides in my assets
folder through xml?
I know how to do that programmatically but how can you do that via xml? Thanks in advance.
5 Answers
You cannot do it using XML directly, however you can extend TextView
and set a default font.
package com.nannu;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class NanTV extends TextView{
private Context c;
public NanTV(Context c) {
super(c);
this.c = c;
Typeface tfs = Typeface.createFromAsset(c.getAssets(),
"font/yourfont.ttf");
setTypeface(tfs);
}
public NanTV(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.c = context;
Typeface tfs = Typeface.createFromAsset(c.getAssets(),
"font/yourfont.ttf");
setTypeface(tfs);
// TODO Auto-generated constructor stub
}
public NanTV(Context context, AttributeSet attrs) {
super(context, attrs);
this.c = context;
Typeface tfs = Typeface.createFromAsset(c.getAssets(),
"font/yourfont.ttf");
setTypeface(tfs);
}
}
And in your layout use new TextView
<com.nannu.NanTV
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
I am posting this from my prev answer https://stackoverflow.com/a/11239305/1166537
If you create your own TextView
derivation, you could add an XML-attribute that the class handles the programmatical way. That way, you specify a certain font and it'll be set runtime, but you do it via XML. :)
Otherwise, there's no known way to achieve the requested behaviour.

- 6,031
- 1
- 26
- 41
-
that sounds good, can you give an example? I don't think a lot of people thought about doing this. – Vinay W Jul 13 '12 at 13:46
-
If you check iNan's example below, it would be along that way (just adding custom attributes & getting them via ``AttributeSet attrs``). My eclipse is broken so I can't quite help you out with the actual code right now. :( – karllindmark Jul 13 '12 at 13:53
I have created a library to solve this problem here: http://responsiveandroid.com/2012/03/15/custom-fonts-in-android-widgets.html
You extend a TextView and set the name of the typeface in the xml. There is a downloadable sample.

- 5,057
- 5
- 29
- 37
you can specify the font in your XML, e.g.
<com.github.browep.customfonts.view.FontableTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is in a custom font"
app:font="MyFont-Bold.otf" />
The code supports FontableTextView and FontableButton, but it's quite easy to extend to support other widget types if you require.

- 41
- 2