Android 全局替换字体

1. 替换全局字体

  1. 需要引入依赖
// 替换全局字体使用
api 'com.android.support:support-v13:28.0.0'
  1. res 目录下创建一个 font 目录,将用到的字体复制进去,然后再创建一个字体的xml。
替换字体01.jpg
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <font
        android:font="@font/pop_ttf"
        android:fontStyle="normal"
        android:fontWeight="400"
        app:font="@font/pop_ttf"
        app:fontStyle="normal"
        app:fontWeight="400" />

    <font
        android:font="@font/pop_ttf"
        android:fontStyle="italic"
        android:fontWeight="400"
        app:font="@font/pop_ttf"
        app:fontStyle="italic"
        app:fontWeight="400" />
</font-family>
  1. 在主题中引用
<!-- 主题样式 -->
<style name="BaseTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <!-- 其他配置 -->
 
    <!-- 设置全局的字体样式 -->
    <item name="android:fontFamily">@font/pop_font</item>
</style>

2. 在实际使用中,发现对 RadioButton 不起作用,所以自定义一个 RadioButton 单独对其进行处理;

  1. 添加属性;
<!-- 自定义 RadioButton -->
<declare-styleable name="MyRadioButton">
    <attr name="textFont" format="reference" />
</declare-styleable>
  1. 继承 RadioButton;
class MyRadioButton @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
) : RadioButton(context, attrs, defStyleAttr) {

    private var textFont: Int = -1

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyRadioButton) //获取我们定义的属性
        textFont = typedArray.getResourceId(R.styleable.MyRadioButton_textFont, -1)

        initView()
        typedArray.recycle()
    }

    private fun initView() {
        if (-1 != textFont) {
            paint.isAntiAlias = true
            val font = ResourcesCompat.getFont(context, textFont)
            paint.typeface = font
        }
    }
}
  1. 使用;
<mm.cme.baselibrary.widgets.MyRadioButton
    android:id="@+id/rb_mine"
    style="@style/MainBtmTabRBtn"
    android:text="我的"
    app:textFont="@font/pop_font" />
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,907评论 1 45
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,292评论 4 61
  • 1 概述 最近项目中要添加表情包聊天的功能(文本和表情包要混合在一起),最直接的解决方案应该就是图文混排,对于这个...
    小芸论阅读 8,734评论 0 3
  • Address:https://www.zybuluo.com/XiangZhou/note/208532 Exp...
    天蠍蒗漫阅读 11,454评论 2 55
  • 说起夏天,西瓜、蒲扇还有凉拖便是其经典物品代名词!现在的代名词似乎只有空调了。 坐在树下摇着蒲扇吃西瓜 小时候,夏...
    小斯卡阅读 427评论 2 3