Set font at runtime, TextView
Asked Answered
C

9

42

How to set the font of a TextView created at runtime?

I created a TextView

Textview tv = new TextView(this);      
tv.setTextSize(20);

I can easily change the size, now I'd like to set font style to "Verdana".

How to do this?

Comptom answered 14/8, 2010 at 11:45 Comment(0)
C
73

To set In-built Font at Run-Time:

  • First of all, To Change Font-face, a Typeface class is used.

  • Now, at Run-Time, to set the font-face, Use setTypeface(Typeface) from the Java code

  • at Design-Time, to set the font-face, Use android:typeface="serif"

For example:

<TextView android:text="@+id/TextView01"
 android:id="@+id/TextView01"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textSize="30px"
 android:textStyle="italic"
 android:typeface="serif" />

To set Custom font(s) in your Android application

To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets. You might, for example, create assets/fonts/ and put your TTF files in there:

  TextView tv=(TextView)findViewById(R.id.custom); 
  Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf"); 
  tv.setTypeface(face); 
Ceaseless answered 14/8, 2010 at 13:35 Comment(3)
one mistake i have found in your example is that font extention not small letter but in capital letter like "fonts/HandmadeTypewriter.TTF"Stamata
the font extention can be either caps TTF or lower case ttf, it just has to match the way it is in your asset folderOctarchy
@NikunjPatel and the extension can also be completely removed.Dorren
W
5

You can have .ttf font in your asset folder. Say font's name is "default.ttf" and you just now have to write below 2 lines of code

TextView text = new TextView(this);
text.setTypeface(Typeface.createFromAsset(getAssets(), "default.ttf"));

You must also we careful because different font have different sizes. You may need to set size as :

text.setTextSize(20);
Wiatt answered 8/4, 2014 at 0:21 Comment(0)
M
5

you can use your font which you have store in font "res/font" ex. for API level 16 and above.

   Typeface typeface = ResourcesCompat.getFont(context, R.font.rubik_medium);
   txtView.setTypeface(typeface);

you can also use

   Typeface typeface = getResources().getFont(R.font.rubik_medium);
   txtView.setTypeface(typeface);

but it support with API level 26 and above.

Malayoindonesian answered 4/3, 2020 at 10:53 Comment(0)
I
3

With introduction of Fonts in XML in Android 8.0 (backward compatible from API version 14) its very easy to set font from xml itself.

From the android documentation:

Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in your R file and are automatically available in Android Studio. You can access the font resources with the help of a new resource type, font. For example, to access a font resource, use @font/myfont, or R.font.myfont.

Firstly create a Android Resource Directory in res folder named as font
Add your .ttf font file to that directory, and then create font family

Create a font family

A font family is a set of font files along with its style and weight details. In Android, you can create a new font family as an XML resource and access it as a single unit, instead of referencing each style and weight as separate resources. By doing this, the system can select the correct font based on the text style you are trying to use.

To create a font family, perform the following steps in the Android Studio:

  1. Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
  2. Enter the file name, and then click OK. The new font resource XML opens in the editor.
  3. Enclose each font file, style, and weight attribute in the <font> element. The following XML illustrates adding font-related attributes in the font resource XML:

    <?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/lobster_regular" /> <font android:fontStyle="italic" android:fontWeight="400" android:font="@font/lobster_italic" /> </font-family>

Then use the following code to set font in your textView like

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lobster"/>
Individualist answered 22/1, 2018 at 11:30 Comment(0)
V
2

Here is a small utility class

public class TypefaceHelper {

    public static void setViewGroupTypeface(ViewGroup container, Typeface typeface) {
        final int children = container.getChildCount();

        for (int i = 0; i < children; i++) 
            View child = container.getChildAt(i);

            if (child instanceof TextView) {
                setTextViewTypeface((TextView) child, typeface);
            } else if (child instanceof ViewGroup) {
                setViewGroupTypeface((ViewGroup) child, typeface);
            }
        }
    }

    public static void setTextViewTypeface(TextView textView, Typeface typeface) {
        textView.setTypeface(typeface);
    }

}

For things like Spinners or ListViews (i.e. any kind of AdapterView) which generate their children from an adapter you will need to set the typeface of each item View in the getView (or similar) method of the adapter. This is because views may be created as needed and so setting the Typeface in onCreate won't work properly.

Vector answered 6/1, 2013 at 15:37 Comment(0)
S
2

Dynamically you can set the fontfamily similar to android:fontFamily in xml by using this,

For Custom font:

 TextView tv = ((TextView) v.findViewById(R.id.select_item_title));
 Typeface face=Typeface.createFromAsset(getAssets(),"fonts/mycustomfont.ttf"); 
 tv.setTypeface(face);

For Default font:

 tv.setTypeface(Typeface.create("sans-serif-medium",Typeface.NORMAL));

These are the list of default font family used, use any of this by replacing the double quotation string "sans-serif-medium"

FONT FAMILY                    TTF FILE                    

1  casual                      ComingSoon.ttf              
2  cursive                     DancingScript-Regular.ttf   
3  monospace                   DroidSansMono.ttf           
4  sans-serif                  Roboto-Regular.ttf          
5  sans-serif-black            Roboto-Black.ttf            
6  sans-serif-condensed        RobotoCondensed-Regular.ttf 
7  sans-serif-condensed-light  RobotoCondensed-Light.ttf   
8  sans-serif-light            Roboto-Light.ttf            
9  sans-serif-medium           Roboto-Medium.ttf           
10  sans-serif-smallcaps       CarroisGothicSC-Regular.ttf 
11  sans-serif-thin            Roboto-Thin.ttf             
12  serif                      NotoSerif-Regular.ttf       
13  serif-monospace            CutiveMono.ttf              

"mycustomfont.ttf" is the ttf file. Path will be in src/assets/fonts/mycustomfont.ttf

Stratification answered 26/7, 2017 at 12:51 Comment(0)
D
2

If you don't want to use typeface and fiddle around with the path to your font file (Which may crash your application if you put in an incorrect path), here's another way.

First create a style in your styles.xml

<style name="YourFont">
    <item name="android:fontFamily">@font/your_font</item>
</style>

Then you can just add the style using

textView.setTextAppearance(context, R.style.YourFont);
Dietsche answered 4/12, 2019 at 19:5 Comment(0)
T
1

You need to use Typeface:

  1. add font you wish to use to your project as asset.
  2. create Typeface object using that font:

    Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/MyFont.ttf");

  3. set typeface to the object you'd like to customize:

    TextView myTextView = (TextView)findViewById(R.id.my_text_view); myTextView.setTypeface(myFont);

Tailgate answered 14/8, 2010 at 11:56 Comment(0)
B
-3

You can use the following code to set all your text to a specific font at runtime. Just call the setViewGroupFont method at the end of your Activity onCreate method or whenever you dynamically create new views:

private static final String FONT_NAME = "fonts/Roboto-Regular.ttf";
private static Typeface m_font = null;

public static Typeface getFont(Context p_context)
{
    if (null == m_font && null != p_context)
    {
        m_font = Typeface.createFromAsset(p_context.getApplicationContext().getAssets(), FONT_NAME);
    }
    return m_font;
}

public static void setViewGroupFont(ViewGroup p_viewGroup)
{
    if (null != p_viewGroup)
    {
        for (int currChildIndex = 0; currChildIndex < p_viewGroup.getChildCount(); currChildIndex++)
        {
            View currChildView = p_viewGroup.getChildAt(currChildIndex);

            if (ViewGroup.class.isInstance(currChildView))
            {
                setViewGroupFont((ViewGroup) currChildView);
            }
            else
            {
                try
                {
                    Method setTypefaceMethod = currChildView.getClass().getMethod("setTypeface", Typeface.class);

                    setTypefaceMethod.invoke(currChildView, getFont(p_viewGroup.getContext()));
                }
                catch (NoSuchMethodException ex)
                {
                    // Do nothing
                }
                catch (Exception ex)
                {
                    // Unexpected error setting font
                }
            }
        }
    }
}
Beechnut answered 22/7, 2012 at 8:10 Comment(4)
Rather than using reflection you should check whether the child is an instance of TextView or ViewGroupVector
Simply Use this :- TextView tv=(TextView)findViewById(R.id.custom); Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf"); tv.setTypeface(face);Chalfant
@JosephEarl @Avin Checking if it's a TextView is not sufficient since you also want to set the font on buttons, radio groups, spinners... (In fact, any control that supports the setTypeface method) - And this is why using reflection is the most general way to do that. If you only wish to set fonts of TextView, you can avoid it but otherwise you'll need to check each and every widget type and cast accordingly.Beechnut
@Beechnut Spinner extends ViewGroup, and Button extends TextView so as I said checking for it being an instance of TextView or ViewGroup is generally sufficient.Vector

© 2022 - 2024 — McMap. All rights reserved.