How to use custom font in a project written in Android Studio
Asked Answered
S

22

272

I was trying to use custom font in Android Studio as we did in Eclipse. But unfortunately could not figure out where to put the 'assets' folder!

Subdued answered 21/12, 2014 at 11:34 Comment(1)
here's the official guide you can check out. developer.android.com/guide/topics/ui/look-and-feel/…Irradiation
S
511

Update 2024:

Create a folder named font inside the res folder and copy your font

enter image description here

All font names must be only: lowercase a-z, 0-9, or underscore.

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

For programmatic use:

textView.setTypeface(ResourcesCompat.getFont(context, R.font.abc_font))

For Android Studio 4.2+ there's even now a menu option:

enter image description here

Subdued answered 21/12, 2014 at 11:34 Comment(8)
Anyone loading custom fonts from assets should note that there is a bug in Android 5.0 where some fonts fail to load. While this issue was fixed in Android 5.1, a workaround for supporting 5.0 is by re-writing out ttf fonts. See this issue for more information #27269764Multiplier
The second option worked perfectly for me. Thanks for this!Sharyl
i used this.getContext().getApplicationContext().getAssets() to find the directory (android studio 2.1)Larimer
@kuthue onCreate() is fine. If you want to change the font while the user is using the app, you can put it at the point you wish it changed. This works also for buttonsDoralyn
How can I set that the default font for the entire project will be that custom one I'm adding? Is that what the first code example is doing?Information
It's not working on actual device Android 8.0 Huwaie Y9 2019 device. Please help!Basilicata
Don't forget to remove any forbidden characters. Example, change it 'CedarvilleCursive-Regular' to it 'cedarville'Swashbuckling
Make sure that your font's filename is correct. "File-based resource names must contain only lowercase a-z, 0-9, or underscore"Borlow
S
106

https://static.mcmap.net/file/mcmap/ZG-AbGLDKwfpKnMAWVMrKmltX1ywKmMva3/i6XNU.png

  1. Select File>New>Folder>Assets Folder

  2. Click finish

  3. Right click on assets and create a folder called fonts

  4. Put your font file in assets > fonts

  5. Use code below to change your textView's font

    TextView textView = (TextView) findViewById(R.id.textView);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/yourfont.ttf");
    textView.setTypeface(typeface);
    
Saline answered 29/9, 2016 at 16:40 Comment(2)
how to use this in xml?Miso
@Miso The Support Library 26 provides full support to this feature on devices running API versions 14 and higher linkSaline
T
72

There are many ways to set custom font family on field and I am using like that below.

To add fonts as resources, perform the following steps in the Android Studio:

1) Right-click the res folder and go to New > Android resource directory. The New Resource Directory window appears.

2) In the Resource type list, select font, and then click OK.

Note: The name of the resource directory must be font.

3) Add your font files in the font folder. enter image description here

Add font in desired view in your xml file:

enter image description here

Note: But you required the following things for that:

  1. Android Studio above to 3.0 canary.

  2. Your Activity extends AppCompatActivity.

  3. Update your Gradle file like that:

    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {        
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

buildtoolsVersion above to 26 and minimum targetSdkVersion required 26

  1. Add dependencies in build.gradle file:
classpath 'com.android.tools.build:gradle:3.0.0-beta4'
  1. gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
Tonry answered 26/9, 2017 at 9:48 Comment(0)
M
50

I think instead of downloading .ttf file we can use Google fonts. It's very easy to implements. only you have to follow these steps. step 1) Open layout.xml of your project and the select font family of text view in attributes (for reference screen shot is attached) enter image description here

step 2) The in font family select More fonts.. option if your font is not there. then you will see a new window will open, there you can type your required font & select the desired font from that list i.e) Regular, Bold, Italic etc.. as shown in below image. enter image description here

step 3) Then you will observe a font folder will be auto generated in /res folder having your selected fonts xml file.

enter image description here

Then you can directly use this font family in xml as

      android:fontFamily="@font/josefin_sans_bold"

or pro grammatically you can achieve this by using

  Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);
  fontText.setTypeface(typeface);
Mohn answered 12/4, 2018 at 13:1 Comment(2)
This isn't an answer to the question. Not every font is available on Google Fonts.Intended
Nice answer! If you can't find your font in the list - load it in. the assets folder or define it through the xmlNarbada
T
22

Hello here we have a better way to apply fonts on EditTexts and TextViews on android at once and apply it in whole project.

First of All you need to make fonts folder. Here are Steps.

1: Go to the (project folder) Then app>src>main

2: Create folders named 'assets/fonts' into the main folder.

3: Put your fonts into the fonts folder. Here I Have 'MavenPro-Regular.ttf'

Here are the Steps for applying custom fonts on EditText and using this approach you can apply fonts on every input.

1 : Create a Class MyEditText (your preferred name ...)

2 : which extends EditText

3 : Apply your font

Here is code Example;

public class MyEditText extends EditText {

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

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyEditText(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/MavenPro-Regular.ttf");
            setTypeface(tf);
        }
    }

}

And in Here is the code how to use it.

MyEditText editText = (MyEditText) findViewById(R.id.editText);

editText.setText("Hello");

Or in Your xml File

   <MyEditText
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:textColor="#fff"
    android:textSize="16dp"
    android:id="@+id/editText"
    />
Tman answered 14/8, 2016 at 5:20 Comment(4)
That class gave me that error on runtime: Error inflating class MyEditTextPickaxe
Refer to this Link you may find some hints how to solve the Error.Tman
#3740161Tman
With the current build, I think you would need to change this to "extends AppCompatEditText".Counterintelligence
B
16

With Support Library 26.0 (and Android O) fonts can be loaded from resource easily with: enter image description here

Typeface typeface = ResourcesCompat.getFont(Context context, int fontResourceId) 

Docs for the method.

More info can be found here.

Baritone answered 19/5, 2017 at 14:22 Comment(0)
M
11

I want to add my answer for Android-O and Android Studio 2.4

  1. Create folder called font under res folder. Download the various fonts you wanted to add to your project example Google fonts

  2. Inside your xml user font family

    example :

    <TextView
        android:fontFamily="@font/indie_flower"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="@string/sample_text" />
    

3.If you want it to be in programmatic way use following code

Typeface typeface = getResources().getFont(R.font.indie_flower);
textView.setTypeface(typeface);

for more information follow the link to my blog post Font styles for Android with Android Studio 2.4

Mete answered 9/4, 2017 at 7:41 Comment(2)
Please note if you want to promote your own product/blog you must disclose your affiliation, otherwise your answer may be flagged as spam. Please read How to not be a spammerRaines
Yes @PetterFribergMete
T
9

As per new feature available in Android O, font resources in XML is avilable as new feature.

To add fonts as resources, perform the following steps in the Android Studio:

1) Right-click the res folder and go to New > Android resource directory. The New Resource Directory window appears.

2) In the Resource type list, select font, and then click OK.

Note: The name of the resource directory must be font.

3) Add your font files in the font folder.

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.

eg. Typeface typeface = getResources().getFont(R.font.myfont); textView.setTypeface(typeface);

Terwilliger answered 24/6, 2017 at 12:40 Comment(1)
should be ResourcesCompat.getFont(context, R.font.your_font)Detrude
S
8

You can use easy & simple EasyFonts third party library to set variety of custom font to your TextView. By using this library you should not have to worry about downloading and adding fonts into the assets/fonts folder. Also about Typeface object creation. You will be free from creating asset folder too.

Simply:

TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(EasyFonts.robotoThin(this));

There are many type of fonts provided by this library.

Scarce answered 25/6, 2015 at 18:10 Comment(0)
B
6
  1. Create folder assets in Project -> app (or your app name) -> src -> main -> right click -> New -> Directory.
  2. Then create a new directory inside assets called "fonts".

To assign the font to the textView:

TextView textView = (TextView) findViewById(R.id.your_textView);

final Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/your_font_name");

your_font_name includes font extension.

Burmese answered 21/12, 2014 at 13:23 Comment(0)
N
6

1st add font.ttf file on font Folder. Then Add this line in onCreate method

    Typeface typeface = ResourcesCompat.getFont(getApplicationContext(), R.font.myfont);
    mytextView.setTypeface(typeface);

And here is my xml

            <TextView
            android:id="@+id/idtext1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="7dp"
            android:gravity="center"
            android:text="My Text"
            android:textColor="#000"
            android:textSize="10sp"
        />
Nobel answered 24/3, 2019 at 6:38 Comment(0)
E
5

To use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26. For more information on using the support library, refer to the Using the support library section.

To add fonts as resources, perform the following steps in the Android Studio:

  1. Right-click the res folder and go to New > Android resource directory.

    The New Resource Directory window appears.

  2. In the Resource type list, select font, and then click OK.

  3. Add your font files in the font folder.

Creating a font family 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 element. The following XML illustrates adding font-related attributes in the font resource XML: If your minSdkVersion is API level 26 and higher

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

and if your minSdkVersion is lower than API level 26

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

Then you can use it any where like this

android:fontFamily="@font/your_custom_font_file"
Epsom answered 24/3, 2021 at 14:3 Comment(0)
C
5

Adding font to your project

To add fonts as resources, perform the following steps in the Android Studio:

1 - Right-click the res folder and go to New > Android resource directory. The New Resource Directory window appears.

2 - In the Resource type list, select font, and then click OK. 3 - Add your font files in the font folder just by a simple copy and paste. note that the name of the fonts should be in lowercase.

Using fonts in XML layouts

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

Adding fonts to style

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

Using fonts programmatically

Kotlin:

val typeface = resources.getFont(R.font.myfont)
textView.typeface = typeface

JAVA:

Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);
Cymatium answered 21/12, 2021 at 5:59 Comment(0)
F
4

If you are very new to Android like I am this can be a little tricky. Make sure you call:

TextView myTextView = (TextView) findViewById(R.id.textView);
Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/your font.ttf");
myTextView.setTypeface(typeface);

method within a method such as onCreate.

Faris answered 27/10, 2016 at 2:12 Comment(0)
F
3

Android 8.0 (API 26) introduced new features related to fonts.

1) Fonts can be used as resources.

2) Downloadable fonts.

If you want to use external fonts in your android application, you can either include font files in apk or configure downloadable fonts.

Including font files in APK : You can download font files, save them in res/font filer, define font family and use font family in styles.

For more details on using custom fonts as resources see http://www.zoftino.com/android-using-custom-fonts

Configuring downloadable fonts : Define font by providing font provider details, add font provider certificate and use font in styles.

For more details on downloadable fonts see http://www.zoftino.com/downloading-fonts-android

Forejudge answered 16/10, 2017 at 4:29 Comment(2)
Official documentation: developer.android.com/guide/topics/ui/look-and-feel/…Siderite
Also, just because Custom/Downloadable fonts were introduced in Android O (8.0), does not mean there's no backwards compatibility for it. Please see the official documentation on how to implement Custom Fonts. Please note you may need Android Studio 3.0 installed as well.Foxglove
P
2

I could not load fonts because I had named my font file Poppins-Medium.tff, renaming it to poppins_medium.tff worked for me. Rest of the steps remained the same:

  • Create the font resource directory under res folder
  • Copy and paste your tff file in that directory
  • Then use in TextView in XML using fontFamily attribute.
  • If above steps dont work, you can create a FontFamily of that font using this link
Pelage answered 18/7, 2020 at 18:4 Comment(0)
A
1

First create assets folder then create fonts folder in it.

Then you can set font from assets or directory like bellow :

public class FontSampler extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        TextView tv = (TextView) findViewById(R.id.custom);
        Typeface face = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");

        tv.setTypeface(face);

        File font = new File(Environment.getExternalStorageDirectory(), "MgOpenCosmeticaBold.ttf");

        if (font.exists()) {
            tv = (TextView) findViewById(R.id.file);
            face = Typeface.createFromFile(font);

            tv.setTypeface(face);
        } else {
            findViewById(R.id.filerow).setVisibility(View.GONE);
        }
    }
} 
Assurbanipal answered 8/5, 2017 at 9:38 Comment(0)
C
1

Add your fonts to assets folder in app/src/main/assets make a custom textview like this :

class CustomLightTextView : TextView {

constructor(context: Context) : super(context){
    attachFont(context)
}
constructor(context: Context, attrs: AttributeSet):    super(context, attrs){
    attachFont(context)
}
constructor(context: Context, attrs: AttributeSet?,    defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    attachFont(context)
}
fun attachFont(context: Context) {
    this.setTypeface(FontCache.getInstance().getLightFont(context))
}

}

Add FontCache : So that you don't have to create typeface again and again like :

class FontCache private constructor(){

val fontMap = HashMap<String,Typeface>()

companion object {
    private var mInstance : FontCache?=null
    fun getInstance():FontCache = mInstance?: synchronized(this){
        return mInstance?:FontCache().also { mInstance=it }
    }
}

fun getLightFont(context: Context):Typeface?{
    if(!fontMap.containsKey("light")){
        Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf");
        fontMap.put("light",Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf"))
    }
    return fontMap.get("light")
}

}

And you are done !

P.S.From android O, you can directly add fonts.

Cookery answered 19/11, 2019 at 13:22 Comment(0)
G
0

Now there are so many ways to apply font one of easiest way is like this, 1) Right-click the res folder go to New > Android resource directory.

2) From Resource type list, select font, and then click OK.

3) Put your font files in the font folder.

Gulledge answered 11/6, 2019 at 13:32 Comment(0)
C
0

put fonts in asset folder then apply fontfamily:''your fonts

Cucurbit answered 29/4, 2020 at 5:13 Comment(0)
M
0

Kotlin Answer

If you need to use fonts in code side, you can use this function also it has version code control.

fun getFontJarvisWhite(): Typeface {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) resources.getFont(R.font.jarvis_white)
    else context?.let { ResourcesCompat.getFont(it, R.font.jarvis_white) }!!
}
Marcellmarcella answered 16/9, 2021 at 15:27 Comment(0)
K
-2

For new readers

You can use this library Gloxey Custom Font Views

gradle dependency

  dependencies{
           compile 'io.gloxey.cfv:custom-font-views:1.0.2'
    }

How to use?

Create folder assets -> fonts. Copy your fonts into fonts folder.

Use property app : font_name = "font_name_string" to apply font on view.

Example

   <!--Font Names in srings.xml-->
       <string name="aadhunik">aadhunik.ttf</string>
       <string name="kung_fool">kungfool.ttf</string>
       <string name="skrova">skrova.otf</string>
       <string name="painting_in_the_sun_light">painting_in_the_sun_light.ttf</string>

   <!--Include views in layout.xml-->
       <io.gloxey.cfv.CFTextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:gravity="center"
       android:text="Aadhunik"
       android:textColor="#ff00"
       android:textSize="40sp"
       app:font_name="@string/aadhunik" />

       <io.gloxey.cfv.CFButton
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Kung Fool"
       android:textColor="#154748"
       app:font_name="@string/kung_fool" />

       <io.gloxey.cfv.CFEditText
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:gravity="center"
       android:text="Hello world"
       android:textSize="30sp"
       app:font_name="@string/skrova" />

       <io.gloxey.cfv.CFCheckBox
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center"
       android:text="Painting In The Sun Light"
       android:textSize="30sp"
       app:font_name="@string/painting_in_the_sun_light" />
Kilauea answered 11/7, 2017 at 8:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.