Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom font in android xml? [duplicate]

How can I use a custom font which was added in the asset folder in my xml? I know we can use setTypeface() method in java, but we have to do this everywhere where we use that TextView. So is there a better way?

like image 661
Vins Avatar asked Jan 27 '12 07:01

Vins


People also ask

How do I use fonts in XML?

Adding fonts to a TextViewIn the layout XML file, set the fontFamily attribute to the font file you want to access. Open the Properties window to set the font for the TextView . Select a view to open the Properties window. Note: The Properties window is available only when the design editor is open.

How do I use different fonts on Android?

Open Settings. Tap Display. Tap Font and screen zoom. Select your choice of Font Style and you're done.

How do I create a TTF file on Android?

Creating a font family To create a font family, perform the following steps in the Android Studio: Right-click the font folder and go to New > Font resource file. The New Resource File window appears. Enter the file name, and then click OK.


Video Answer


1 Answers

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.

like image 84
Vins Avatar answered Oct 14 '22 16:10

Vins