本文介绍: 产品告诉UI设计设计图时要使用炫酷字体。因为Android不像网页项目可以使用浏览器本机字体,Android只有那几种字体

目录

前言

①使用typeface 方式

一、创建加载字体实例


   产品告诉UI设计设计图时要使用炫酷字体。因为Android不像网页项目可以使用浏览器本机字体,Android只有那几种字体

可以使用两种方法

typeface值如下

fontFamily 值如下

sansserif

sansserif-condensed

sansserif-smallcaps

serif

serif-monospace

monospace

casual

cursive

 fontFamily优先级大于typeface优先级


可以查看下面Android常用字体

Android自带字体https://blog.csdn.net/weixin_41620505/article/details/114673516

使用反射方式


import android.content.Context
import android.graphics.Typeface

object FontsOverride {

/**
*staticTypefaceFieldName :最好是 normal、sans、serif、monospace其中一个
*/
    fun setDefaultFont(context: Context, staticTypefaceFieldName: String, fontAssetName: String?) {
        val regular = Typeface.createFromAsset(context.assets, fontAssetName)
        replaceFont(staticTypefaceFieldName, regular)
    }

    internal fun replaceFont(staticTypefaceFieldName: String, newTypeface: Typeface?) {
        try {
            val staticField = Typeface::class.java.getDeclaredField(staticTypefaceFieldName)
            staticField.isAccessible = true
            staticField[null] = newTypeface
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
    }
}

要把字体ttf文件放到assets/fonts目录下,没有目录手动创建

//staticTypefaceFieldName :最好是 normal、sans、serif、monospace其中一个
FontsOverride.setDefaultFont(this, "SERIF", "fonts/pangmenzhengdaobiaoti.ttf")

代码如下(示例):

    <TextView
                android:id="@+id/newHomeLoction" 
                android:textColor="@color/white"
                android:textSize="26sp"
                android:typeface="serif"
                app:layout_constraintStart_toStartOf="@+id/newHomeLeaveTitle"
                app:layout_constraintTop_toBottomOf="@+id/newHomeLeaveTitle" />

下图所示

        <TextView
                android:id="@+id/newHomeLoction"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:gravity="bottom|end"
                android:includeFontPadding="false"
                android:paddingBottom="28dp"
                android:fontFamily="@font/pangiaoti"
                android:text="字体水水水水" />

总结

使用typeface这种方式不用每一个TextView都需要写,因为有默认字体样式(monospace)

使用fontFamily方式需要每一个TextView需要写一遍

 在xml布局使用的

1:

android:typeface

2:

android:fontFamily

做好区分

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注