Android中快速實現自定義字體!


前言:我們都知道,Android中默認的字體是黑體,而大多數app也都是使用的這種字體,但我們發現,大多數app中,個別地方字體非常好看,例如app的標題欄,菜單欄等地方,那他們是怎么做到的呢?有兩種方式,第一是圖片來代替文字,第二,就是今天我要教大家的自定義字體。

開發環境:

Android Studio 2.2.2

compileSdkVersion 25

buildToolsVersion "25.0.0"

minSdkVersion 19

targetSdkVersion 25

compile 'com.android.support:appcompat-v7:25.0.0'

提示:使用項目時注意開發環境的更改,以免造成不必要的時間浪費。

1自定義字體

說到字體,我們不難聯想到我們使用office時可以選擇的各種字體,我們就是需要這種字體文件,值得一提的是,Windows提供了很多字體文件,可以在C:\Windows\Fonts找到。當然,我們也可以去網絡上下載你喜歡的字體文件。字體文件是ttf格式的喲。

那我們現在就開始,我們先把要使用的字體文件放入到工具中,操作如下:

(1)新建一個名叫assets的文件夾,然后把字體文件復制到里面

STXINGKA.TTF就是字體文件

(2)我們新建一個類,名叫FontCustom,寫入代碼:

public class FontCustom {
 
    // fongUrl是自定義字體分類的名稱
    private static String fongUrl = "STXINGKA.TTF";
    //Typeface是字體,這里我們創建一個對象
    private static Typeface tf;
 
    /**
     * 設置字體
     */
    public static Typeface setFont(Context context)
    {
        if (tf == null)
        {
            //給它設置你傳入的自定義字體文件,再返回回來
            tf = Typeface.createFromAsset(context.getAssets(),fongUrl);
        }
        return tf;
    }
}

(3)新建一個類名叫MyTextView繼承TextView,重寫2個參數的構造方法

public class MyTextView extends TextView {
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    /**
     * 初始化字體
     * @param context
     */
    private void init(Context context) {
        //設置字體樣式
        setTypeface(FontCustom.setFont(context));
    }
}

2使用自定義字體類

我們復制MyTextView的路徑到activity_main中,替換原有的TextView,我這里的路徑是

com.example.fengjun.fontdiy.MyTextView

修改activity_main中的代碼:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"    tools:context="com.example.fengjun.fontdiy.MainActivity">
 
    <com.example.fengjun.fontdiy.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        android:text="Hello!我是自定義字體" />

</RelativeLayout>

效果很酷炫,對不對?我們只需要2個類就可以完成了自定義字體,之后再哪里需要使用自定義字體,就把路徑替換原有的TextView就完成了!

3總結

自定義字體在我們的程序中其實用的地方不多,大多數時候,我們都喜歡用圖片來代替TextView來作為標題名稱等特殊地方。如果我們在程序中展示的文字內容,使用自定義字體,那就是非常棒的選擇,會給人一種耳目一新的感覺。

 項目下載地址:http://pan.baidu.com/s/1pLhKgbh

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM