How to set a particular font for a button text in android?
Solution 1
If you plan to add the same font to several buttons I suggest that you go all the way and implement it as a style and subclass button:
public class ButtonPlus extends Button {
public ButtonPlus(Context context) {
super(context);
}
public ButtonPlus(Context context, AttributeSet attrs) {
super(context, attrs);
CustomFontHelper.setCustomFont(this, context, attrs);
}
public ButtonPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
CustomFontHelper.setCustomFont(this, context, attrs);
}
}
This is a helper class to set a font on a TextView (remember, Button is a subclass of TextView) based on the com.my.package:font attribute:
public class CustomFontHelper {
/**
* Sets a font on a textview based on the custom com.my.package:font attribute
* If the custom font attribute isn't found in the attributes nothing happens
* @param textview
* @param context
* @param attrs
*/
public static void setCustomFont(TextView textview, Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFont);
String font = a.getString(R.styleable.CustomFont_font);
setCustomFont(textview, font, context);
a.recycle();
}
/**
* Sets a font on a textview
* @param textview
* @param font
* @param context
*/
public static void setCustomFont(TextView textview, String font, Context context) {
if(font == null) {
return;
}
Typeface tf = FontCache.get(font, context);
if(tf != null) {
textview.setTypeface(tf);
}
}
}
And here's the FontCache to reduce memory usage on older devices:
public class FontCache {
private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();
public static Typeface get(String name, Context context) {
Typeface tf = fontCache.get(name);
if(tf == null) {
try {
tf = Typeface.createFromAsset(context.getAssets(), name);
}
catch (Exception e) {
return null;
}
fontCache.put(name, tf);
}
return tf;
}
}
In res/values/attrs.xml we define the custom styleable attribute
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFont">
<attr name="font" format="string"/>
</declare-styleable>
</resources>
And finally an example use in a layout:
<com.my.package.buttons.ButtonPlus
style="@style/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_sometext"/>
And in res/values/style.xml
<style name="button" parent="@android:style/Widget.Button">
<item name="com.my.package:font">fonts/copperplate_gothic_light.TTF</item>
</style>
This may seem like an awful lot of work, but you'll thank me once you have couple of handfuls of buttons and textfields that you want to change font on.
Solution 2
1) Get the font you need as a .ttf (CopperplateGothicLight.ttf for example) file and place it in your project's /assets/ directory
2) Use this code to refer to the font and set it to your button:
Typeface copperplateGothicLight = Typeface.createFromAsset(getAppContext().getAssets(), "CopperplateGothicLight.ttf");
yourButton.setTypeface(copperplateGothicLight);
Solution 3
After several research, my best option was :
public class CustomButton extends Button {
Typeface normalTypeface = FontCache.get("fonts/CopperplateGothicLight.ttf", getContext());
Typeface boldTypeface = FontCache.get("fonts/CopperplateGothicBold.ttf", getContext());
/**
* @param context
*/
public CustomButton(Context context) {
super(context);
}
/**
* @param context
* @param attrs
*/
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* @param context
* @param attrs
* @param defStyleAttr
*/
public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
then Using fontCache from the 1st answer on this : Memory leaks with custom font for set custom font
public class FontCache {
private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();
public static Typeface get(String name, Context context) {
Typeface tf = fontCache.get(name);
if(tf == null) {
try {
tf = Typeface.createFromAsset(context.getAssets(), name);
}
catch (Exception e) {
return null;
}
fontCache.put(name, tf);
}
return tf;
}
}
Less code and more usage of the android standards !
Solution 4
MainActivity.java
package com.mehuljoisar.customfontdemo;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button1.setTypeface(Typeface.createFromAsset(getAssets(), "copperplate-gothic-light.ttf"));
button1.setText("hello");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="24dp"
android:text="Button" />
Download link for your desired font: copperplate_gothic_light
put it inside your asset folder.
Screenshot:
I hope it will be helpful !!
![Garima Tiwari](https://i.stack.imgur.com/ltJ1z.jpg?s=256&g=1)
Comments
-
Garima Tiwari almost 3 years
I want my button text to be in the Copperplate Gothic Light font and I yet have not come across a simple clean code for a simple function as this. Help!
PS: Since android comes with ariel and a few other fonts on its own we need to import (apologies for the lack of a better word since I'm new to this) the font we wish to use. This is all I have been able to gather till yet and this is where the trail ends for me.
-
Garima Tiwari about 11 yearsWhere do I get this .ttf file you talk about? Im extremely new to this so I'll need a little patience, thank you.
-
npace about 11 yearsIt's a TrueType font file. If you do not have a .ttf for your font, just search Google or something, I'm sure there are tons of free fonts you can use.
-
britzl about 11 years"Firstly you can not set Custom font style from XML file". This is wrong. You can define a custom style attribute and subclass Button. See my answer.
-
Garima Tiwari about 11 yearsHey that's very thoughtful because I do have to implement it through a million activities.
-
Garima Tiwari about 11 yearsHey, I did that. Downloaded the thingy off the internet and put it in my assets folder but it doesn't seem to recognize it. Does the name of the folder has to be same or do i put in the font name itself?
-
Mehul Joisar about 11 years@GarimaTiwari:look at the screenshot,you need to put that
.ttf
file in yourassets
folder and you need to use same file name while setting typeface to the button. -
Mehul Joisar about 11 years@GarimaTiwari:if you want to apply the font at many places,answer of
britzl
is better for your case.make custom view by extendingButton
to get rid of memory leaks occurs whilecreateFromAsset
method in each activity. -
baldguy about 11 years@britzl Oh I dnt know that.. Thanks for such useful info.
-
britzl about 11 yearsTake care with memory use on older devices if you don't cache the Typeface (I think the bug was solved in newer Android versions): code.google.com/p/android/issues/detail?id=9904
-
britzl about 11 yearsTake care with memory use on older devices if you don't cache the Typeface (I think the bug was solved in newer Android versions): code.google.com/p/android/issues/detail?id=9904
-
gnclmorais over 10 yearsThis is one of the most helpful answers I have found around StackOverflow. Thank you!
-
Tom S. over 9 yearsFantastic response. Out of curiosity why bother with FontCache as a separate class from the CustomFontHelper? I combined those and applied this to both buttons and textviews.
-
britzl over 9 yearsOff the top of my head I can't think of a good reason for separating them other than that you may want to use the FontCache in other circumstances as well.
-
denvercoder9 over 9 yearsNice answer! But you could also override the setTypeface method.
-
Prashanth Debbadwar over 7 yearsit is not working? where are you applying custom font?
-
Teo Inke over 7 yearsWhat about the first constructor not setting the custom font? Is it not the one called when using Buttons in xml? (I truly don't know that)
-
Shashanth over 7 yearsHmm. Posted the same answer here also. :)
-
MashukKhan over 7 yearsCan you explain style.xml?? Coz, I didn't got that the item name is upto the font package or upto the font.ttf file??
-
Chathuranga Shan about 6 yearsCan't Thank you enough. I had a project ready to publish but only 2 RecyclerView in that app was lagging when user scroll only in the devices which had low free ram and free storage. I always suspected that is happens due to custom fonts I set because that list item had more than 10 TextViews with different fonts. After following your answer now that problem is fixed.