I want to use a custom font for my android application which I am creating.
I can individually change the typeface of each object from Code, but I have hundreds of them.
So,
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
Yes It is possible.
You have to create a custom view which extends text view.
In attrs.xml
in values
folder:
<resources>
<declare-styleable name="MyTextView">
<attr name="first_name" format="string"/>
<attr name="last_name" format="string"/>
<attr name="ttf_name" format="string"/>
</declare-styleable>
</resources>
In main.xml
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:lht="http://schemas.android.com/apk/res/com.lht"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello"/>
<com.lht.ui.MyTextView
android:id="@+id/MyTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello friends"
lht:ttf_name="ITCBLKAD.TTF"
/>
</LinearLayout>
In MyTextView.java
:
package com.lht.ui;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class MyTextView extends TextView {
Context context;
String ttfName;
String TAG = getClass().getName();
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
for (int i = 0; i < attrs.getAttributeCount(); i++) {
Log.i(TAG, attrs.getAttributeName(i));
/*
* Read value of custom attributes
*/
this.ttfName = attrs.getAttributeValue(
"http://schemas.android.com/apk/res/com.lht", "ttf_name");
Log.i(TAG, "firstText " + firstText);
// Log.i(TAG, "lastText "+ lastText);
init();
}
}
private void init() {
Typeface font = Typeface.createFromAsset(context.getAssets(), ttfName);
setTypeface(font);
}
@Override
public void setTypeface(Typeface tf) {
// TODO Auto-generated method stub
super.setTypeface(tf);
}
}