当前位置: 动力学知识库 > 问答 > 编程问答 >

android - How to change typeface of a TextView in the xml?

问题描述:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: