更改Android应用程序的默认字体

4

好的,我知道如何更改应用程序中单个文本框使用的字体,但我希望应用程序中所有文本都使用这种自定义字体和颜色,目前我能想到的唯一方法是引用每个文本框并将它们设置为正确的字体和颜色。虽然这样做是可行的,但似乎有点笨拙,有没有更好的方法?


我认为你必须编写自己的样式和/或主题。请参考以下有用的答案:https://dev59.com/T2oy5IYBdhLWcg3wEKFo 或 https://dev59.com/r2855IYBdhLWcg3wXC1- 或者这个https://dev59.com/B3A85IYBdhLWcg3wCe9Z。 - JJ86
3个回答

8

您可以创建自定义的TextView,并在任何地方引用它。

public class TypefacedTextView extends TextView {

    public TypefacedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        Typeface typeface = Typeface.createFromAsset(context.getAssets(), fontName);
        setTypeface(typeface);
    }
}

内部 view.xml

<packagename.TypefacedTextView
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="Hello"/>

1
我正准备提交相同的答案 :) - gunar

2
将不同的字体文件放在assets文件夹中...
TextView mytextView=(TextView)findViewById(R.id.txtbx);
Typeface fonttype=Typeface.createFromAsset(getAssets(),"fonts/fontname.ttf");
mytextView.setTypeface(fonttype);

0
通过在字体资源文件中创建Font-Family元素并将您的字体系列添加到应用程序主题中,在res>values>styles>中。
----------
<resources>
<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <!--Add this below line-->
        <item name="android:fontFamily">@font/PacificoRegular</item>
    </style>
</resources>


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