Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change typeface of a TextView in the xml?

Tags:

android

I have been googling around, but haven't found a solution for this.

I know I can change the font of a TextView programatically like this view.setTypeface(Typeface.createFromAsset(getAssets(),"dejavusans.ttf"));.

But, isn't there a way to do it directly in the xml file? I have found android:typeface attribute but it only have the options of "normal", "sans, "serif" and "monospace". How can I use this font I have in /assets/fonts/Roboto-Regular.ttf?

Thanks.

like image 638
nunos Avatar asked Jan 17 '23 18:01

nunos


1 Answers

I wrote a library project that can do this. It's called Nifty: https://github.com/tom-dignan/nifty

With nifty, you can specify typefaces in your assets dir from your styles.xml file or as an attribute directly in your XML layout. It provides a custom NiftyTextView and NiftyButton that inherit all the functionality of their parent classes except provide the ability to specify the typeface in XML.

Example Style:

<style name="MyStyle" parent="@android:style/Theme">
        <item name="typeface">my_font_that_is_in_assets.ttf</item>
</style>

Example XML:

 <com.tomdignan.nifty.NiftyTextView
        android:id="@+id/title"
        style="@style/MyStyle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />    

Alternatively, if you are not using a style:

 <com.tomdignan.nifty.NiftyTextView
            xmlns:nifty="http://schemas.tomdignan.com/nifty"
            nifty:typeface="my_font_that_is_in_assets.ttf"
            android:id="@+id/title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />  

Get nifty

Caveats: Custom views are not previewable in the layout editor. My way of working around this is using a search/replace.

like image 67
Thomas Dignan Avatar answered Jan 29 '23 10:01

Thomas Dignan