文章目的:快速入門Android中自定義各種字體!
前言:我們都知道,Android中默認(rèn)的字體是黑體,而大多數(shù)app也都是使用的這種字體,但我們發(fā)現(xiàn),大多數(shù)app中,個別地方字體非常好看,例如app的標(biāo)題欄,菜單欄等地方,那他們是怎么做到的呢?有兩種方式,第一是圖片來代替文字,第二,就是今天我要教大家的自定義字體。
一 自定義字體
說到字體,我們不難聯(lián)想到我們使用office時可以選擇的各種字體,我們就是需要這種字體文件,值得一提的是,Windows提供了很多字體文件,可以在C:\Windows\Fonts找到。當(dāng)然,我們也可以去網(wǎng)絡(luò)上下載你喜歡的字體文件。字體文件是ttf格式的喲。
那我們現(xiàn)在就開始,我們先把要使用的字體文件放入到工具中,操作如下:
(1)新建一個名叫assets的文件夾,然后把字體文件復(fù)制到里面


Mogra-Regular.ttf就是字體文件
(2)我們新建一個類,名叫FontCustom,寫入代碼:
import android.content.Context;
import android.graphics.Typeface;
/**
* author : i小灰
* desc :自定義字體
*/
public class FontCustom {
// fongUrl是自定義字體分類的名稱
private static String fongUrl = "Mogra-Regular.ttf";
//Typeface是字體,這里我們創(chuàng)建一個對象
private static Typeface tf;
/**
* 設(shè)置字體
*/
public static Typeface setFont(Context context)
{
if (tf == null)
{
//給它設(shè)置你傳入的自定義字體文件,再返回回來
tf = Typeface.createFromAsset(context.getAssets(),fongUrl);
}
return tf;
}
}
(3)新建一個類名叫MyTextView繼承TextView,重寫2個參數(shù)的構(gòu)造方法
import android.content.Context;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatTextView;
/**
* author : i小灰
* desc :自定義字體
*/
public class MyTextView extends AppCompatTextView {
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
/**
* 初始化字體
* @param context
*/
private void init(Context context) {
//設(shè)置字體樣式
setTypeface(FontCustom.setFont(context));
}
}
使用自定義字體類
我們復(fù)制MyTextView的路徑到activity_main中,替換原有的TextView,我這里的路徑是
com.my.customfont.font.MyTextView
修改activity_main中的代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.my.customfont.font.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello 我是i小灰!"
android:textSize="25sp" />
</LinearLayout>
好了,到這里,我們就完成了自定義字體,現(xiàn)在我們運行程序看看效果!

方法及說明
1.create(String familyName, int style)
創(chuàng)建給定一個familyName 字體Typeface對象,并選擇樣式信息
2.create(Typeface family, int style)
創(chuàng)建一個字體對象指定的現(xiàn)有字體和指定的風(fēng)格最適合
3.createFromFile(String path)
創(chuàng)建一個從指定的字體文件的新字體
4.defaultFromStyle(int style)
返回一個默認(rèn)的字體對象的基礎(chǔ)上指定的樣式
5.getStyle()
返回字樣的內(nèi)在樣式屬性
之后再哪里需要使用自定義字體,就把路徑替換原有的TextView !
總結(jié):
自定義字體在我們的程序中其實用的地方不多,大多數(shù)時候,我們都喜歡用圖片來代替TextView來作為標(biāo)題名稱等特殊地方。如果我們在程序中展示的文字內(nèi)容,使用自定義字體,那就是非常棒的選擇,會給人一種耳目一新的感覺。
項目下載地址:https://pan.baidu.com/s/1Av_64Xz3z2Uf6BWPiNS3yw 提取碼:1234
分享一個flutter項目,作為學(xué)習(xí) OpenJMU
歡迎關(guān)注 i小灰 帶你學(xué)習(xí)新知識!