APP端

Android 全局替换字体

2019-03-26  本文已影响0人  ChenME

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" />
上一篇 下一篇

猜你喜欢

热点阅读