如何在xml中更改TextView的字体?

4

我已经搜索了很多,但还没有找到解决方案。

我知道可以像这样在程序中改变TextView的字体:view.setTypeface(Typeface.createFromAsset(getAssets(),"dejavusans.ttf"));

但是,在xml文件中有没有直接进行更改的方法呢?我发现android:typeface属性只有"normal"、"sans"、"serif"和"monospace"等选项。那我该如何使用位于/assets/fonts/Roboto-Regular.ttf中的字体呢?

谢谢。


我认为没有办法。你为什么不想用Java方法来完成它? - FoamyGuy
1
https://dev59.com/33E95IYBdhLWcg3wSb7P - vbokan
1
似乎没有在XML中更改TextView字体的方法。 - user1378730
1个回答

9
我写了一个库项目可以实现这个功能,它叫做 Nifty: https://github.com/tom-dignan/nifty 使用 Nifty,您可以在 styles.xml 文件中从 assets 目录指定字体,也可以直接在 XML 布局中作为属性指定。它提供了一个自定义的 NiftyTextView 和 NiftyButton,继承了它们父类的所有功能,并提供了在 XML 中指定字体的能力。
示例样式:
<style name="MyStyle" parent="@android:style/Theme">
        <item name="typeface">my_font_that_is_in_assets.ttf</item>
</style>

示例 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" />    

如果您没有使用样式:

或者,如果您没有使用样式表:

(更加通俗易懂)
 <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" />  

获取nifty

注意事项:自定义视图无法在布局编辑器中预览。我的解决方法是使用搜索/替换。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接