Android自定義字體實(shí)踐

寫在開始

對比ios系統(tǒng),Android中默認(rèn)的字體在中文顯示上是十分難看的,尤其是字號比較大的時候,默認(rèn)字體樣式都會感覺比較粗,所以一般對于產(chǎn)品有追求的設(shè)計,都會考慮換一套字體樣式,那么過程中就需要知道一些自定義字體的知識。這里的自定義系列翻譯于一個看過比較好的系列,因?yàn)樵拿科钠悬c(diǎn)少,所以將幾篇文章合在一起翻譯。

原文地址

為什么自定義字體

Android系統(tǒng)默認(rèn)使用的是一款叫Roboto的字體。如果你想要突出一個元素,那么會有很多的選擇:顏色,大小,樣式(粗體,斜體,普通),另一種方式就是使用不同于系統(tǒng)的字體來裝飾你的view。

單個用法的最快實(shí)現(xiàn)

首先你需要去找一些想使用的 ttf 文件,比較好的地方有1001 Free Fonts或者是Google Fonts
然后,將這個文件放在Android項目的 assets 文件夾下面。

font files in our eat foody project

然后就是將這個字體運(yùn)用到你想要改變的 TextView 上面。

TextView textview = (TextView) findViewById(R.id.your_referenced_textview);
 // adjust this line to get the TextView you want to change

Typeface typeface = Typeface.createFromAsset(getAssets(),"SourceSansPro-Regular.ttf"); // create a typeface from the raw ttf  
textview.setTypeface(typeface); // apply the typeface to the textview 

然后就結(jié)束了,如果想要改變一個Textview的字體就是這么簡單,最好的情況就是上面的代碼在 onCreate() 方法中進(jìn)行調(diào)用。
如果你只想用在單個實(shí)例上那么這種方法是足夠的,但是如果你想要給app中成千上萬的view都使用自定義字體的話,這可能就不是一個好方法了,畢竟我們不可能在每個初始化的地方都去加上上面那一段。

提供字體內(nèi)存緩存

雖然Android現(xiàn)在已經(jīng)很流暢,但是我們依然應(yīng)該考慮優(yōu)化性能。所以,我們應(yīng)該把自定義的字體緩存起來,這樣就不用每次去初始化,在 britzl on stackoverflow上有一個比較好的答案。

public class FontCache {

    private static HashMap<String, Typeface> fontCache = new HashMap<>();

    public static Typeface getTypeface(String fontname, Context context) {
        Typeface typeface = fontCache.get(fontname);

        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), fontname);
            } catch (Exception e) {
                return null;
            }

            fontCache.put(fontname, typeface);
        }

        return typeface;
    }
}

緩存下字體就能讓我們不用一直去操作 Assets 文件夾,接下來就能實(shí)現(xiàn)一個繼承自 TextView 的類。

繼承TextView

首先來創(chuàng)建一個類繼承自 TextView,這樣就能在 XML 中來使用,它繼承了 TextView所有的屬性和功能,然后再加上自定義的字體。

public class EatFoodyTextView extends TextView {

    public EatFoodyTextView(Context context) {
        super(context);

        applyCustomFont(context);
    }

    public EatFoodyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        applyCustomFont(context);
    }

    public EatFoodyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        applyCustomFont(context);
    }

    private void applyCustomFont(Context context) {
        Typeface customFont = FontCache.getTypeface("SourceSansPro-Regular.ttf", context);
        setTypeface(customFont);
    }
}

開始的三個都是構(gòu)造函數(shù),里面都調(diào)用了 applyCustomFont() 方法,然后從上面的 FontCache 類中拿到緩存的字體文件,這樣就不用每個view都去重復(fù)的從 Assets中取字體,節(jié)約了資源,最后將取到的字體設(shè)置到 setTypeface() 中。

使用自定義類

現(xiàn)在我們只需要在XML中直接使用,不需要再寫其他的java代碼,

<RelativeLayout  
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.futurestudio.foody.views.EatFoodyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/eat_foody_green_dark"
        android:textSize="20sp"
        android:text="Future Studio Blog"
        android:layout_marginBottom="24dp"/>

</RelativeLayout> 

我們可以依然使用TextView的其他屬性,(textSize,textColor之類的),只需要把 <TextView/> 替換成 <com.futurestudio.foody.views.EatFoodyTextView/> ,這個前面的是全部的包名,然后就會自己應(yīng)用字體。
但是使用中會發(fā)現(xiàn),雖然一些TextView的屬性比如 textSize 能正常的顯示,但是 textStyle 這個屬性并不能正常的生效。

添加每個ttf文件

首先將同一個系列的三種樣式的 ttf 文件都加到 assets

Assets Folder with Font Files for Each Style

在XML中使用textStyle屬性

在前面已經(jīng)講解了自定義view的使用

<io.futurestud.tutorials.customfont.CustomFontTextView  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="12dp"
    android:text="http://futurestud.io/blog/"
    android:textSize="18sp"
    android:textStyle="bold"/>

一般情況下,我們更希望使用的是標(biāo)準(zhǔn)的 android:textStyle 而不是用一個自定義的屬性 customfont:textStyle 。但是像上面這樣的屬性直接放上去肯定是不能生效的,還需要再加一些代碼才行。
提示:如果你對使用 customfont:textStyle 的方式比較感興趣,那么下一篇文章中會介紹如何使用。

實(shí)現(xiàn)CustomFontTextView

為了能繼續(xù)的使用系統(tǒng)的 android:textStyle 屬性,需要一些步驟。
首先需要在代碼拿到這個屬性的信息,這只需要一行代碼:

int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL); 

attr 這個值是來自 TextView 的第二個構(gòu)造函數(shù)中的參數(shù),我們可以使用這個對象的 getAttributeIntValue() 方法獲取XML的屬性。
先看一下上面代碼中的 ANDROID_SCHEMA 這個參數(shù),這個是一個常量,定義在XML的最頂部中(xmlns:android="http://schemas.android.com/apk/res/android" ),第二個參數(shù)就是定義的屬性名,最后一個參數(shù)是默認(rèn)值,如果這個屬性沒有設(shè)置,那么就會選擇 Typeface.NORMAL
當(dāng)我們考慮了樣式之后,完善一下代碼,全部的代碼看起來就像下面這樣。

public class CustomFontTextView extends TextView {

    public static final String ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android";

    public CustomFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        applyCustomFont(context, attrs);
    }

    public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        applyCustomFont(context, attrs);
    }

    private void applyCustomFont(Context context, AttributeSet attrs) {
        int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL);

        Typeface customFont = selectTypeface(context, textStyle);
        setTypeface(customFont);
    }

    private Typeface selectTypeface(Context context, int textStyle) {
        /*
        * information about the TextView textStyle:
        * http://developer.android.com/reference/android/R.styleable.html#TextView_textStyle
        */
        switch (textStyle) {
            case Typeface.BOLD: // bold
                return FontCache.getTypeface("SourceSansPro-Bold.ttf", context);

            case Typeface.ITALIC: // italic
                return FontCache.getTypeface("SourceSansPro-Italic.ttf", context);

            case Typeface.BOLD_ITALIC: // bold italic
                return FontCache.getTypeface("SourceSansPro-BoldItalic.ttf", context);

            case Typeface.NORMAL: // regular
            default:
                return FontCache.getTypeface("SourceSansPro-Regular.ttf", context);
        }
}

這樣我們的自定義字體就能使用標(biāo)準(zhǔn)的應(yīng)用字體樣式 textStyle

看看成果

首先我們在XML中寫一些布局,包括原生的 Roboto 字體以及不同形式的自定義字體。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:text="http://futurestud.io/blog/"
        android:textSize="18sp"/>

    <io.futurestud.tutorials.customfont.CustomFontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:text="http://futurestud.io/blog/"
        android:textSize="18sp"/>

    <io.futurestud.tutorials.customfont.CustomFontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:text="http://futurestud.io/blog/"
        android:textSize="18sp"
        android:textStyle="bold"/>

    <io.futurestud.tutorials.customfont.CustomFontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:text="http://futurestud.io/blog/"
        android:textSize="18sp"
        android:textStyle="italic"/>

</LinearLayout> 

這個文件在模擬器上顯示的效果就像下面這樣。

Fonts from top to bottom: Roboto, Source Sans Pro, Source Sans Pro Bold, Source Sans Pro Italic
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,662評論 25 708
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,153評論 4 61
  • 知道思維導(dǎo)圖緣于《最強(qiáng)大腦》這檔節(jié)目,知道了原來有記憶法和思維導(dǎo)圖這兩樣工具,也聽說了思維導(dǎo)圖有助于提高邏輯、記憶...
    文魁大腦孫承君閱讀 382評論 0 0
  • 早上準(zhǔn)備上班前打開手機(jī),看到微信上她的留言。有關(guān)繪本,有關(guān)閱讀的導(dǎo)向性,還有有關(guān)喜歡與否等等問題。現(xiàn)在有個習(xí)慣,看...
    hattie_pan閱讀 413評論 0 0
  • 今天我和媽媽在兒童公園打秋千。一個鐵管兒上掛著四個秋千。有兩個隔著遠(yuǎn)的鐵管。人多,大家都在玩兒,所以沒有空...
    山藥粉閱讀 742評論 4 2