Accessing a font under assets folder from XML file in Android

Viewed 80099

I am trying to do a application-wide font change and creating a style file to do so. In this file (below) I just want to change typeface value of TextAppearance style of Android.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="NightRiderFont" parent="@android:style/TextAppearance">
        <item name="android:typeface"> /***help need here***/ </item>
    </style>
</resources>

However font is in "assets/fonts/". How can I access this font, so I can use that style as a theme to get rid of changing all TextViews by hand programatically.

As summary: How can I access 'a file from assets folder' in XML?

14 Answers

Instead of assets folder, you can put the .ttf file on fonts folder. To use fonts support in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26+. Right click res folder, new -> Android resource directory-> select font -> Ok. put your "myfont.ttf" file in newly created font folder.

On res/values/styles.xml add,

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

On layout file add android:textAppearance="@style/customfontstyle",

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/customfontstyle"/>

Refer : https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml

//accessing font file in code,

Typeface type = Typeface.createFromAsset(getResources().getAssets(),"fonts/arial.ttf");
textView.setTypeface(type);//assign typeface to textview

//in assets folder->fonts(foldername)->arial.ttf(font file name)

Related