Android之全局替换字体库

Android O推出了一项新的功能「Fonts in XML」(中文翻译),借助这项功能,我们能够像使用其他资源文件一样使用字体,比较方便地实现App全局字体的替换。

前提

需要下载Android O(API 26)的build-tools等,Android Studio的版本需为3.0以上(2.3的编译无法通过)

获取字体库文件

Android中支持ttf和otf格式的字体库文件,需要提供两个字体库文件(fontStyle:默认和斜体,我这里只是为了测试,fontStyle两种都用了同一个字体库),由于该功能是Android O才开始支持的,所以需要使用support library(支持14以上版本)的支持,在build.gradle中添加支持库

implementation 'com.android.support:support-v13:26.1.0'

font资源文件中需要使用app前缀(支持库的属性)


字体资源文件

编写style.xml

<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>
        <!--字体库-->
        <item name="android:fontFamily">@font/cursive</item>
    </style>

在style中添加,基本上就可以了

自定义View中的使用

在自定义View中使用canvas#drawText绘制字体时,默认还是显示的原有字体,如果也需要替换,需要设置Paint的Typeface

public class FontTestView extends View {
    private Paint mPaint;

    public FontTestView(Context context) {
        this(context, null);
    }

    public FontTestView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FontTestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(40);
        Typeface font = ResourcesCompat.getFont(context, R.font.cursive);
        mPaint.setTypeface(font);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText("测试字体显示效果", 20, 50, mPaint);
    }
}

最终效果

  • TextView
  • Button
  • 自定义View
最终效果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,381评论 25 708
  • 红颜伊人,洛水之边 梳妆弄袖,载笑载言 华姿秀裙,媚态柳荑 采薇并作,楚眸清妍 魂凰容若,樱口微颔 我自南山,夙夜...
    皇氏三墳阅读 196评论 0 0
  • 有很多人, 从第一次尝试过失败了, 就打算放弃了。 有更多人, 就连尝试的勇气都没有, 就直接自我否定了。 200...
    黑糖玛奇朵黑糖话梅阅读 349评论 0 1
  • 十里桃花 桃花十里 春风中 相思的白浅 等你 夜华君 第三世的 相遇 牵手 相依 爱 从凡尘开启 受伤的小黑蛇 被...
    lsjr陈浮阅读 466评论 5 4