How to change the font on the TextView?

AndroidFontsTextview

Android Problem Overview


How to change the font in a TextView, as default it's shown up as Arial? How to change it to Helvetica?

Android Solutions


Solution 1 - Android

First, the default is not Arial. The default is Droid Sans.

Second, to change to a different built-in font, use android:typeface in layout XML or setTypeface() in Java.

Third, there is no Helvetica font in Android. The built-in choices are Droid Sans (sans), Droid Sans Mono (monospace), and Droid Serif (serif). While you can bundle your own fonts with your application and use them via setTypeface(), bear in mind that font files are big and, in some cases, require licensing agreements (e.g., Helvetica, a Linotype font).

EDIT

> The Android design language relies on traditional typographic tools > such as scale, space, rhythm, and alignment with an underlying grid. > Successful deployment of these tools is essential to help users > quickly understand a screen of information. To support such use of > typography, Ice Cream Sandwich introduced a new type family named > Roboto, created specifically for the requirements of UI and > high-resolution screens. > > The current TextView framework offers Roboto in thin, light, regular > and bold weights, along with an italic style for each weight. The > framework also offers the Roboto Condensed variant in regular and bold > weights, along with an italic style for each weight.

After ICS, android includes Roboto fonts style, Read more Roboto

EDIT 2

> With the advent of Support Library 26, Android now supports custom fonts by > default. You can insert new fonts in res/fonts which can be set to TextViews individually either in XML or programmatically. The default font for the whole application can also be changed by defining it styles.xml The android developer documentation has a clear guide on this here

Solution 2 - Android

First download the .ttf file of the font you need (arial.ttf). Place it in the assets folder. (Inside assets folder create new folder named fonts and place it inside it.) Use the following code to apply the font to your TextView:

Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf"); 
textView.setTypeface(type);

Solution 3 - Android

Typeface tf = Typeface.createFromAsset(getAssets(),
        "fonts/DroidSansFallback.ttf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf);

Solution 4 - Android

You might want to create static class which will contain all the fonts. That way, you won't create the font multiple times which might impact badly on performance. Just make sure that you create a sub-folder called "fonts" under "assets" folder.

Do something like:

public class CustomFontsLoader {

public static final int FONT_NAME_1 = 	0;
public static final int FONT_NAME_2 = 	1;
public static final int FONT_NAME_3 = 	2;

private static final int NUM_OF_CUSTOM_FONTS = 3;

private static boolean fontsLoaded = false;

private static Typeface[] fonts = new Typeface[3];

private static String[] fontPath = {
	"fonts/FONT_NAME_1.ttf",
	"fonts/FONT_NAME_2.ttf",
	"fonts/FONT_NAME_3.ttf"
};


/**
 * Returns a loaded custom font based on it's identifier. 
 * 
 * @param context - the current context
 * @param fontIdentifier = the identifier of the requested font
 * 
 * @return Typeface object of the requested font.
 */
public static Typeface getTypeface(Context context, int fontIdentifier) {
	if (!fontsLoaded) {
		loadFonts(context);
	}
	return fonts[fontIdentifier];
}


private static void loadFonts(Context context) {
	for (int i = 0; i < NUM_OF_CUSTOM_FONTS; i++) {
		fonts[i] = Typeface.createFromAsset(context.getAssets(), fontPath[i]);
	}
	fontsLoaded = true;
	
}
}

This way, you can get the font from everywhere in your application.

Solution 5 - Android

Best practice ever

TextViewPlus.java:

public class TextViewPlus extends TextView {
    private static final String TAG = "TextView";

    public TextViewPlus(Context context) {
        super(context);
    }

    public TextViewPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }

    public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
        String customFont = a.getString(R.styleable.TextViewPlus_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface typeface = null;
        try {
            typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
        } catch (Exception e) {
            Log.e(TAG, "Unable to load typeface: "+e.getMessage());
            return false;
        }

        setTypeface(typeface);
        return true;
    }
}

attrs.xml: (Where to place res/values)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TextViewPlus">
        <attr name="customFont" format="string"/>
    </declare-styleable>
</resources>

How to use:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:foo="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.mypackage.TextViewPlus
        android:id="@+id/textViewPlus1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:text="@string/showingOffTheNewTypeface"
        foo:customFont="my_font_name_regular.otf">
    </com.mypackage.TextViewPlus>
</LinearLayout>

Hope this will help you.

Solution 6 - Android

The answers above are correct. Just make sure that you create a sub-folder called "fonts" under "assets" folder if you are using that piece of code.

Solution 7 - Android

Another way to consolidate font creation...

public class Font {
  public static final Font  PROXIMA_NOVA    = new Font("ProximaNovaRegular.otf");
  public static final Font  FRANKLIN_GOTHIC = new Font("FranklinGothicURWBoo.ttf");
  private final String      assetName;
  private volatile Typeface typeface;

  private Font(String assetName) {
    this.assetName = assetName;
  }

  public void apply(Context context, TextView textView) {
    if (typeface == null) {
      synchronized (this) {
        if (typeface == null) {
          typeface = Typeface.createFromAsset(context.getAssets(), assetName);
        }
      }
    }
    textView.setTypeface(typeface);
  }
}

And then to use in your activity...

myTextView = (TextView) findViewById(R.id.myTextView);
Font.PROXIMA_NOVA.apply(this, myTextView);

Mind you, this double-checked locking idiom with the volatile field only works correctly with the memory model used in Java 1.5+.

Solution 8 - Android

Best practice is to use Android Support Library version 26.0.0 or above.

STEP 1: add font file

  1. In res folder create new font resource dictionary
  2. Add font file (.ttf, .orf)

For example, when font file will be helvetica_neue.ttf that will generates R.font.helvetica_neue

STEP 2: create font family

  1. In font folder add new resource file
  2. Enclose each font file, style, and weight attribute in the element.

For example:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/helvetica_neue" />
</font-family>

STEP 3: use it

In xml layouts:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/my_font"/>

Or add fonts to style:

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>

For more examples you can follow documentation:

> Working with fonts

Solution 9 - Android

When your font is stored inside res/asset/fonts/Helvetica.ttf use the following:

Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf"); 
txt.setTypeface(tf);

Or, if your font file is stores inside res/font/helvetica.ttf use the following:

Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);

Solution 10 - Android

It's a little old, but I improved the class CustomFontLoader a little bit and I wanted to share it so it can be helpfull. Just create a new class with this code.

 import android.content.Context;
 import android.graphics.Typeface;

public enum FontLoader {

ARIAL("arial"),
TIMES("times"),
VERDANA("verdana"),
TREBUCHET("trbuchet"),
GEORGIA("georgia"),
GENEVA("geneva"),
SANS("sans"),
COURIER("courier"),
TAHOMA("tahoma"),
LUCIDA("lucida");	

 
private final String name;
private Typeface typeFace;


private FontLoader(final String name) {
	this.name = name;
	
	typeFace=null;	
}

public static Typeface getTypeFace(Context context,String name){
	try {
		FontLoader item=FontLoader.valueOf(name.toUpperCase(Locale.getDefault()));
		if(item.typeFace==null){				
			item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");					
		}			
		return item.typeFace;
	} catch (Exception e) {			
		return null;
	}					
}
public static Typeface getTypeFace(Context context,int id){
	FontLoader myArray[]= FontLoader.values();
	if(!(id<myArray.length)){			
		return null;
	} 
	try {
		if(myArray[id].typeFace==null){		
			myArray[id].typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+myArray[id].name+".ttf");						
		}		
		return myArray[id].typeFace;	
	}catch (Exception e) {			
		return null;
	}	

}

public static Typeface getTypeFaceByName(Context context,String name){		
	for(FontLoader item: FontLoader.values()){ 				
		if(name.equalsIgnoreCase(item.name)){
			if(item.typeFace==null){
				try{
					item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");		
				}catch (Exception e) {			
					return null;
				}	
			}
			return item.typeFace;
		}				
	}
	return null;
}	

public static void loadAllFonts(Context context){		
	for(FontLoader item: FontLoader.values()){ 				
		if(item.typeFace==null){
			try{
				item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");		
			}catch (Exception e) {
				item.typeFace=null;
			}	
		}				 
	}		
}	
}

Then just use this code on you textview:

 Typeface typeFace=FontLoader.getTypeFace(context,"arial");	 
 if(typeFace!=null) myTextView.setTypeface(typeFace);

Solution 11 - Android

I finally got a very easy solution to this.

  1. use these Support libraries in app level gradle,

    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.0.2'
    
  2. then create a directory named "font" inside the res folder

  3. put fonts(ttf) files in that font directory, keep in mind the naming conventions [e.g.name should not contain any special character, any uppercase character and any space or tab]

  4. After that, reference that font from xml like this

            <Button
            android:id="@+id/btn_choose_employee"
            android:layout_width="140dp"
            android:layout_height="40dp"
            android:layout_centerInParent="true"
            android:background="@drawable/rounded_red_btn"
            android:onClick="btnEmployeeClickedAction"
            android:text="@string/searching_jobs"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:fontFamily="@font/times_new_roman_test"
            />
    

In this example, times_new_roman_test is a font ttf file from that font directory

Solution 12 - Android

import java.lang.ref.WeakReference;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Typeface;

public class FontsManager {

	private static FontsManager instance;

	private static HashMap<String, WeakReference<Typeface>> typefaces = new HashMap<String, WeakReference<Typeface>>();

	private static Context context;

	private FontsManager(final Context ctx) {
		if (context == null) {
			context = ctx;
		}
	}

	public static FontsManager getInstance(final Context appContext) {
		if (instance == null) {
			instance = new FontsManager(appContext);
		}
		return instance;
	}

	public static FontsManager getInstance() {
		if (instance == null) {
			throw new RuntimeException(
					"Call getInstance(Context context) at least once to init the singleton properly");
		}
		return instance;
	}

	public Typeface getFont(final String assetName) {
		final WeakReference<Typeface> tfReference = typefaces.get(assetName);
		if (tfReference == null || tfReference.get() == null) {
			final Typeface tf = Typeface.createFromAsset(context.getResources().getAssets(),
					assetName);
			typefaces.put(assetName, new WeakReference<Typeface>(tf));
			return tf;
		}
		return tfReference.get();
	}

}

This way, you can create a View which inherits from TextView and calls setTypeface on its constructor.

Solution 13 - Android

get font from asset and set to all children

public static void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
         }
        } else if (v instanceof TextView ) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(),"DroidNaskh.ttf"));// "BKOODB.TTF"));
        }
    } catch (Exception e) {
 }
 } 

Solution 14 - Android

  1. add class FontTextView.java:


public class FontTextView extends TextView {
    String fonts[] = {"HelveticaNeue.ttf", "HelveticaNeueLight.ttf", "motschcc.ttf", "symbol.ttf"};

    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (!isInEditMode()) {
            init(attrs);
        }

    }

    public FontTextView(Context context) {
        super(context);
        if (!isInEditMode()) {
            init(null);
        }
    }

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
            if (a.getString(R.styleable.FontTextView_font_type) != null) {
                String fontName = fonts[Integer.valueOf(a.getString(R.styleable.FontTextView_font_type))];

                if (fontName != null) {
                    Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/" + fontName);
                    setTypeface(myTypeface);
                }
                a.recycle();
            }
        }
    }
}


  1. add to assets library font
    enter image description here


  1. add to attrs.xml , The numbers should be in the order in array class.

     <declare-styleable name="FontTextView">
     <attr name="font_type" format="enum">
         <enum name="HelveticaNeue" value="0"/>
         <enum name="HelveticaNeueLight" value="1"/>
         <enum name="motschcc" value="2"/>
         <enum name="symbol" value="3"/>
     </attr>
    


  1. Select a font from the list
    enter image description here

Solution 15 - Android

Android uses the Roboto font, which is a really nice looking font, with several different weights (regular, light, thin, condensed) that look great on high density screens.

Check below link to check roboto fonts:

https://stackoverflow.com/questions/34444616/how-to-use-roboto-in-xml-layout/34445295#34445295

Back to your question, if you want to change the font for all of the TextView/Button in your app, try adding below code into your styles.xml to use Roboto-light font:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ......
    <item name="android:buttonStyle">@style/MyButton</item>
    <item name="android:textViewStyle">@style/MyTextView</item>
</style>

<style name="MyButton" parent="@style/Widget.AppCompat.Button">
    <item name="android:textAllCaps">false</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="MyTextView" parent="@style/TextAppearance.AppCompat">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

And don't forget to use 'AppTheme' in your AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    ......
</application>

Solution 16 - Android

Maybe something a bit simpler:

public class Fonts {
  public static HashSet<String,Typeface> fonts = new HashSet<>();
  
  public static Typeface get(Context context, String file) {
    if (! fonts.contains(file)) {
      synchronized (this) {
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), name);
        fonts.put(name, typeface);
      }
    }
    return fonts.get(file);
  }
}

// Usage
Typeface myFont = Fonts.get("arial.ttf");

(Note this code is untested, but in general this approach should work well.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPraveenView Question on Stackoverflow
Solution 1 - AndroidCommonsWareView Answer on Stackoverflow
Solution 2 - AndroidHjKView Answer on Stackoverflow
Solution 3 - AndroidAndroid GirlView Answer on Stackoverflow
Solution 4 - AndroidDaniel L.View Answer on Stackoverflow
Solution 5 - AndroidHiren PatelView Answer on Stackoverflow
Solution 6 - AndroidVJ Vélan SolutionsView Answer on Stackoverflow
Solution 7 - AndroidChris AitchisonView Answer on Stackoverflow
Solution 8 - AndroidMarek RzeźniczekView Answer on Stackoverflow
Solution 9 - AndroidPankaj LilanView Answer on Stackoverflow
Solution 10 - AndroidAlanView Answer on Stackoverflow
Solution 11 - AndroidShamsul Arefin SajibView Answer on Stackoverflow
Solution 12 - AndroidCharlie-BlakeView Answer on Stackoverflow
Solution 13 - AndroidManian RezaeeView Answer on Stackoverflow
Solution 14 - Androiddavid View Answer on Stackoverflow
Solution 15 - AndroidChandlerView Answer on Stackoverflow
Solution 16 - AndroidtransView Answer on Stackoverflow