Android设置本地字体文件ttf

目录

前言

①使用typeface 方式

一、创建加载字体实例

二、使用步骤

1.在Application中加载字体

2.在xml中使用

②使用fontFamily 方式

1、在res/font下导入ttf文件

 2、在xml中使用

总结


前言

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

可以使用两种方法:

  • android:typeface="serif"
  • android:fontFamily="@font/xxxx"

typeface值如下

fontFamily 值如下

sans-serif

sans-serif-condensed

sans-serif-smallcaps

serif

serif-monospace

monospace

casual

cursive

 fontFamily优先级大于typeface优先级


可以查看下面Android常用字体库

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

①使用typeface 方式

一、创建加载字体实例

使用的反射方式


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()
        }
    }
}

二、使用步骤

1.在Application中加载字体

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

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

2.在xml中使用

代码如下(示例):

    <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" />

②使用fontFamily 方式

1、在res/font下导入ttf文件

如下图所示:

 2、在xml中使用

        <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

做好区分

猜你喜欢

转载自blog.csdn.net/weixin_41620505/article/details/128632616