Tarik
Tarik

Reputation: 81721

How to change fontFamily of TextView in Android

So I'd like to change the android:fontFamily in Android but I don't see any pre-defined fonts in Android. How do I select one of the pre-defined ones? I don't really need to define my own TypeFace but all I need is something different from what it shows right now.

<TextView
    android:id="@+id/HeaderText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="52dp"
    android:gravity="center"
    android:text="CallerBlocker"
    android:textSize="40dp"
    android:fontFamily="Arial"
 />

It seems what I did up there won't really work! BTW android:fontFamily="Arial" was a stupid attempt!

Upvotes: 840

Views: 1067015

Answers (30)

kumod kumar yadav
kumod kumar yadav

Reputation: 11

If you want to change font weight of text from adapter then you can use below.

holder.bindingItem.parentTitle.setTypeface(holder.bindingItem.parentTitle.typeface, Typeface.BOLD)

make sure to import ----->>>>> import android.graphics.Typeface and remove import androidx.compose.ui.text.font.Typeface if conflicts exist.

Upvotes: 0

gauravdott
gauravdott

Reputation: 420

I am using the excellent library Calligraphy by Chris Jenx designed to allow you to use custom fonts in your android application. Give it a try!

Upvotes: 15

Gnod
Gnod

Reputation: 155

Here you can see all the available font-family values and their corresponding font file names(This file is used in android 5.0+). On a mobile device, you can find it in:

/system/etc/fonts.xml (for 5.0+)

(For android 4.4 and below using this version, but I think that fonts.xml has a more clear format and is easy to understand.)

For example,

    <!-- first font is default -->
20    <family name="sans-serif">
21        <font weight="100" style="normal">Roboto-Thin.ttf</font>
22        <font weight="100" style="italic">Roboto-ThinItalic.ttf</font>
23        <font weight="300" style="normal">Roboto-Light.ttf</font>
24        <font weight="300" style="italic">Roboto-LightItalic.ttf</font>
25        <font weight="400" style="normal">Roboto-Regular.ttf</font>
26        <font weight="400" style="italic">Roboto-Italic.ttf</font>
27        <font weight="500" style="normal">Roboto-Medium.ttf</font>
28        <font weight="500" style="italic">Roboto-MediumItalic.ttf</font>
29        <font weight="900" style="normal">Roboto-Black.ttf</font>
30        <font weight="900" style="italic">Roboto-BlackItalic.ttf</font>
31        <font weight="700" style="normal">Roboto-Bold.ttf</font>
32        <font weight="700" style="italic">Roboto-BoldItalic.ttf</font>
33    </family>

The name attribute name="sans-serif" of family tag defined the value you can use in android:fontFamily.

The font tag defines the corresponded font files.

In this case, you can ignore the source under <!-- fallback fonts -->, it's used for fonts' fallback logic.

Upvotes: -1

Fr&#233;d&#233;ric
Fr&#233;d&#233;ric

Reputation: 77

Here is an easier way that can work in some cases. The principle is to add a not visible TextVview in your xml layout and to get its typeFace in the java code.

The layout in the xml file:

<TextView
    android:text="The classic bread is made of flour hot and salty. The classic bread is made of flour hot and salty. The classic bread is made of flour hot and salty."
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:fontFamily="sans-serif-thin"
    android:id="@+id/textViewDescription"/>

And the java code:

myText.setTypeface(textViewSelectedDescription.getTypeface());

It has worked for me (within a TextSwitcher for example).

Upvotes: 4

Shubham Raitka
Shubham Raitka

Reputation: 1052

If you want to use a TextView in so many places with the same font family, extend the TextView class and set your font like this:-

public class ProximaNovaTextView extends TextView {
    public ProximaNovaTextView(Context context) {
        super(context);
        applyCustomFont(context);
    }
    public ProximaNovaTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        applyCustomFont(context);
    }
    public ProximaNovaTextView(Context context, AttributeSet attrs, int defStyle) {
       super(context, attrs, defStyle);
       applyCustomFont(context);
    } 
    private void applyCustomFont(Context context) {
        Typeface customFont = FontCache.getTypeface("proximanova_regular.otf", context);
        setTypeface(customFont);
    }
}

And then use this custom class in XML for the TextView like this:-

<com.myapp.customview.ProximaNovaTextView
android:id="@+id/feed_list_item_name_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
/>

Upvotes: 2

Setmax
Setmax

Reputation: 1034

I use Letter Press lib for my NonTextView stuff like Buttons and kianoni fontloader lib for my TextViews cause of usage of style in this lib is easier than Letter Press for me and I got ideal feedback with that. this is great for those who want to use a custom font except Roboto Font. so it was my experience with font libs. for those who want to use a custom class to change the font, I highly recommended creating this class with this snippet

public class TypefaceSpan extends MetricAffectingSpan {
    /** An <code>LruCache</code> for previously loaded typefaces. */
    private static LruCache<String, Typeface> sTypefaceCache =
            new LruCache<String, Typeface>(12);

    private Typeface mTypeface;

    /**
     * Load the {@link android.graphics.Typeface} and apply to a {@link android.text.Spannable}.
     */
    public TypefaceSpan(Context context, String typefaceName) {
        mTypeface = sTypefaceCache.get(typefaceName);

        if (mTypeface == null) {
            mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                    .getAssets(), String.format("fonts/%s", typefaceName));

            // Cache the loaded Typeface
            sTypefaceCache.put(typefaceName, mTypeface);
        }
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }
} 

And use class like this :

AppData = PreferenceManager.getDefaultSharedPreferences(this);
TextView bannertv= (TextView) findViewById(R.id.txtBanner);
    SpannableString s = new SpannableString(getResources().getString(R.string.enterkey));
    s.setSpan(new TypefaceSpan(this, AppData.getString("font-Bold",null)), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    bannertv.setText(s);

maybe this help.

Upvotes: 0

Ali Khaki
Ali Khaki

Reputation: 1212

For android-studio 3 and above you can use this style and then all textView font changes in-app.

create this style in your style.xml :

<!--OverRide all textView font-->
<style name="defaultTextViewStyle" parent="android:Widget.TextView">
        <item name="android:fontFamily">@font/your_custom_font</item>
</style>

Then use it in your theme :

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textViewStyle">@style/defaultTextViewStyle</item>
</style>

Upvotes: 2

mohamad sheikhi
mohamad sheikhi

Reputation: 394

Try this:

TextView textview = (TextView) findViewById(R.id.textview);
Typeface tf= Typeface.createFromAsset(getAssets(),"fonts/Tahoma.ttf");
textview .setTypeface(tf);

Upvotes: 6

Makvin
Makvin

Reputation: 3629

Typeface typeface = ResourcesCompat.getFont(context, R.font.font_name);
textView.setTypeface(typeface);

set easily font to any textview from res>font directory programmatically

Upvotes: 26

Rehan Sarwar
Rehan Sarwar

Reputation: 1004

I think I am too late but maybe this solution helpful for others. For using a custom font place your font file in your font directory.

textView.setTypeface(ResourcesCompat.getFont(this, R.font.lato));

Upvotes: 21

Siva
Siva

Reputation: 176

If you are using Android Studio 3.5+, Changing the font is super simple. Select the text widget on the Design view and check the font family on Attribute Window. The value dropdown contains all the available fonts from which you can select one. If you are looking for Google Fonts, Click the More Fonts option.

Attribute Window Attribute Window

Google Fonts Google Fonts

Upvotes: 11

MdBasha
MdBasha

Reputation: 451

To set the font by program, write...

 TextView tv7 = new TextView(this);
 tv7.setText(" TIME ");    
 tv7.setTypeface(Typeface.create("sans-serif-condensed",Typeface.BOLD));
 tv7.setTextSize(12);
 tbrow.addView(tv7);

The name "sans-serif-condensed" is referenced from the fonts.xml file which should be created in-app--> res--> values folder and it holds the fonts in it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="font_family_light">sans-serif-light</string>
    <string name="font_family_medium">sans-serif-medium</string>
    <string name="font_family_regular">sans-serif</string>
    <string name="font_family_condensed">sans-serif-condensed</string>
    <string name="font_family_black">sans-serif-black</string>
    <string name="font_family_thin">sans-serif-thin</string>
</resources>

Hope this is clear!

Upvotes: 5

Bitlejuce Do
Bitlejuce Do

Reputation: 340

Probably my comment will be useful for somebody: I was trying to realize why app:fontFamily="@font/my_font"doesn't work and after wasting some time found that the working solution is android:fontFamily="@font/my_font"

Upvotes: 1

Bholendra Singh
Bholendra Singh

Reputation: 1156

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

    <font
        android:font="@font/google_sans_italic"
        android:fontStyle="italic"
        android:fontWeight="400"
        app:font="@font/google_sans_italic"
        app:fontStyle="italic"
        app:fontWeight="400" />

    <font
        android:font="@font/google_sans_medium"
        android:fontStyle="normal"
        android:fontWeight="500"
        app:font="@font/google_sans_medium"
        app:fontStyle="normal"
        app:fontWeight="500" />

    <font
        android:font="@font/google_sans_medium_italic"
        android:fontStyle="italic"
        android:fontWeight="500"
        app:font="@font/google_sans_medium_italic"
        app:fontStyle="italic"
        app:fontWeight="500" />

    <font
        android:font="@font/google_sans_bold"
        android:fontStyle="normal"
        android:fontWeight="600"
        app:font="@font/google_sans_bold"
        app:fontStyle="normal"
        app:fontWeight="600" />

    <font
        android:font="@font/google_sans_bold_italic"
        android:fontStyle="italic"
        android:fontWeight="600"
        app:font="@font/google_sans_bold_italic"
        app:fontStyle="italic"
        app:fontWeight="600" />

</font-family>

Upvotes: 0

Pratik Dodiya
Pratik Dodiya

Reputation: 2667

Kotlin Code - Textview to set custom font from Resource Folder

Set custom font from res -> font -> avenir_next_regular.ttf

textView!!.typeface = ResourcesCompat.getFont(context!!, R.font.avenir_next_regular)

Upvotes: 35

EpicPandaForce
EpicPandaForce

Reputation: 81539

You can define a custom FontFamily like this:

/res/font/usual.xml:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:ignore="UnusedAttribute">
    <font
        android:fontStyle="normal"
        android:fontWeight="200"
        android:font="@font/usual_regular"
        app:fontStyle="normal"
        app:fontWeight="200"
        app:font="@font/usual_regular" />

    <font
        android:fontStyle="italic"
        android:fontWeight="200"
        android:font="@font/usual_regular_italic"
        app:fontStyle="italic"
        app:fontWeight="200"
        app:font="@font/usual_regular_italic" />

    <font
        android:fontStyle="normal"
        android:fontWeight="600"
        android:font="@font/usual_bold"
        app:fontStyle="normal"
        app:fontWeight="600"
        app:font="@font/usual_bold" />

    <font
        android:fontStyle="italic"
        android:fontWeight="600"
        android:font="@font/usual_bold_italic"
        app:fontStyle="italic"
        app:fontWeight="600"
        app:font="@font/usual_bold_italic" />
</font-family>

Now you can do

android:fontFamily="@font/usual"

Assuming your other font resources are there as well, with lowercase letters and _s.

Upvotes: 3

Akanshi Srivastava
Akanshi Srivastava

Reputation: 1500

One simple way is by adding the desired font in the project.

Go to File->New->New Resource Directory Select font

This will create a new directory, font, in your resources.

Download your font (.ttf). I use https://fonts.google.com for the same

Add that to your fonts folder then use them in the XML or programmatically.

XML -

<TextView 
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/your_font"/>

Programatically -

 Typeface typeface = ResourcesCompat.getFont(this, R.font.your_font);
 textView.setTypeface(typeface); 

Upvotes: 23

Azizur Rehman
Azizur Rehman

Reputation: 2113

The new font resource allows to directly set font using

android:fontFamily="@font/my_font_in_font_folder"

Upvotes: 2

Wolfiebae
Wolfiebae

Reputation: 395

You can also do this by adding a font folder under the res directory like below.

enter image description here

Then, selecting Font as the resource type. enter image description here

You can find avaliable fonts from https://www.1001fonts.com/, and then extracting the TTF files to this font directory.

enter image description here

Finally, just change the XML file that contains your textview by adding android:fontFamily:"@font/urfontfilename"

enter image description here

Upvotes: 8

CoolMind
CoolMind

Reputation: 28793

You can also change standard fonts with setTextAppearance (requires API 16), see https://stackoverflow.com/a/36301508/2914140:

<style name="styleA">
    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
<style name="styleB">
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?android:attr/textColorTertiary</item>
</style>


if(condition){
    TextViewCompat.setTextAppearance(textView, R.style.styleA);
} else {
    TextViewCompat.setTextAppearance(textView,R.style.styleB);
}

Upvotes: 2

Shivam Yadav
Shivam Yadav

Reputation: 1018

There is a nice library available for this

    implementation 'uk.co.chrisjenx:calligraphy:2.3.0'

Upvotes: 1

androidEnthusiast
androidEnthusiast

Reputation: 1160

The easiest way to add the font programatically to a TextView is to, first, add the font file in your Assets folder in the project. For example your font path is looking like this: assets/fonts/my_font.otf

And add it to a TextView as:

Kotlin

val font_path = "fonts/my_font.otf"  

myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)

textView.typeface = myTypeface

Java

String font_path = "fonts/my_font.otf";
Typeface myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)
textView.setTypeface(myTypeface);

Upvotes: 1

Manohar
Manohar

Reputation: 23394

Starting from Android-Studio 3.0 its very easy to change font family

Using support library 26, it will work on devices running Android API version 16 and higher

Create a folder font under res directory .Download the font which ever you want and paste it inside font folder. The structure should be some thing like below

Here

Note: As of Android Support Library 26.0, you must declare both sets of attributes ( android: and app: ) to ensure your fonts load on devices running Api 26 or lower.

Now you can change font in layout using

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

To change Programatically

 Typeface typeface = getResources().getFont(R.font.myfont);
   //or to support all versions use
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
 textView.setTypeface(typeface);  

To change font using styles.xml create a style

 <style name="Regular">
        <item name="android:fontFamily">@font/dancing_script</item>
        <item name="fontFamily">@font/dancing_script</item>
        <item name="android:textStyle">normal</item>
 </style>

and apply this style to TextView

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/Regular"/>

you can also Create your own font family

- 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. The new font resource XML opens in the editor.

Write your own font family here , for example

<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>

this is simply a mapping of a specific fontStyle and fontWeight to the font resource which will be used to render that specific variant. Valid values for fontStyle are normal or italic; and fontWeight conforms to the CSS font-weight specification

1. To change fontfamily in layout you can write

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

2. To Change Programmatically

 Typeface typeface = getResources().getFont(R.font.lobster);
   //or to support all versions use
Typeface typeface = ResourcesCompat.getFont(context, R.font.lobster);
 textView.setTypeface(typeface);  

To change font of entire App Add these two lines in AppTheme

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
     <item name="android:fontFamily">@font/your_font</item>
     <item name="fontFamily">@font/your_font</item>
  </style>

See the Documentation , Android Custom Fonts Tutorial For more info

Upvotes: 290

Syed Danish Haider
Syed Danish Haider

Reputation: 1384

try these simple steps. 1. create font folder in res folder. 2. copy and paste .ttf file into font folder. 3. Now give the path in xml like below.

 android:fontFamily="@font/frutiger"

or what ever your file name is. Thats it happy code

Upvotes: 0

anand krish
anand krish

Reputation: 4415

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 , you can refer more about default font in this Default font family

Upvotes: 9

Stoycho Andreev
Stoycho Andreev

Reputation: 6283

I just want to mention that the hell with the fonts inside Android is about to end, because this year on Google IO we finally got this -> https://developer.android.com/preview/features/working-with-fonts.html

Now there is a new resource type a font and you can place all your application fonts inside res/fonts folder and access then with R.font.my_custom_font, just like you can access string res values, drawable res values etc. You have even chance to create font-face xml file, which is gonna be set of your custom fonts (about italic, bold and underline attr).

Read the link above for more info. Let's see the support.

Upvotes: 2

Sanny Nagveker
Sanny Nagveker

Reputation: 418

You can do it easy way by using following library

https://github.com/sunnag7/FontStyler

<com.sunnag.fontstyler.FontStylerView
              android:textStyle="bold"
              android:text="@string/about_us"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingTop="8dp"
              app:fontName="Lato-Bold"
              android:textSize="18sp"
              android:id="@+id/textView64" />

its light weight and easy to implement, just copy your fonts in asset folder and use name in xml.

Upvotes: 0

Raghav Sood
Raghav Sood

Reputation: 82553

Android doesn't allow you to set custom fonts from the XML layout. Instead, you must bundle the specific font file in your app's assets folder, and set it programmatically. Something like:

TextView textView = (TextView) findViewById(<your TextView ID>);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "<file name>");
textView.setTypeface(typeFace);

Note that you can only run this code after setContentView() has been called. Also, only some fonts are supported by Android, and should be in a .ttf (TrueType) or .otf (OpenType) format. Even then, some fonts may not work.

This is a font that definitely works on Android, and you can use this to confirm that your code is working in case your font file isn't supported by Android.

Android O Update: This is now possible with XML in Android O, based on Roger's comment.

Upvotes: 51

Jakob Eriksson
Jakob Eriksson

Reputation: 18767

From android 4.1 / 4.2 / 5.0, the following Roboto font families are available:

android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
android:fontFamily="sans-serif-black"     // roboto black
android:fontFamily="sans-serif-thin"      // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium"    // roboto medium (android 5.0)

enter image description here

in combination with

android:textStyle="normal|bold|italic"

this 16 variants are possible:

  • Roboto regular
  • Roboto italic
  • Roboto bold
  • Roboto bold italic
  • Roboto-Light
  • Roboto-Light italic
  • Roboto-Thin
  • Roboto-Thin italic
  • Roboto-Condensed
  • Roboto-Condensed italic
  • Roboto-Condensed bold
  • Roboto-Condensed bold italic
  • Roboto-Black
  • Roboto-Black italic
  • Roboto-Medium
  • Roboto-Medium italic

fonts.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="font_family_light">sans-serif-light</string>
    <string name="font_family_medium">sans-serif-medium</string>
    <string name="font_family_regular">sans-serif</string>
    <string name="font_family_condensed">sans-serif-condensed</string>
    <string name="font_family_black">sans-serif-black</string>
    <string name="font_family_thin">sans-serif-thin</string>
</resources>

Upvotes: 1753

nano_nano
nano_nano

Reputation: 12523

This is the way to set the font programmatically:

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

put the font file in your assets folder. In my case I created a subdirectory called fonts.

EDIT: If you wonder where is your assets folder see this question

Upvotes: 247

Related Questions