Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義字體樣式實現

編輯:關於 Android 程式設計

在 Android 中設置自定義字體,通常通過 Typeface 來完成。先看看官方提供的方法:

顧名思義,我們可以通過項目 assets 目錄下的字體文件,或者 Android 系統自帶的字體文件來完成設置。

方式一:加載 assets 中的字體

首先在項目路徑下創建 assets 文件夾,並把字體文件放進去:

然後直接通過 Typeface 加載並應用即可:

Typeface typeface1 = Typeface.createFromAsset(this.getAssets(), "fonts/1.TTF");
tvText1.setTypeface(typeface1);

如果不想每個控件都手動設置,也可以自定義一個 TextView 的子類,在內部統一加載字體:

public class MyTextView extends TextView {
    public MyTextView(Context context) {
        super(context);
    }
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    public void setTypeface(Typeface tf, int style) {
        super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "2.ttf"));
    }
}

這樣一來,只要在布局裡使用 MyTextView,就能自動套用自定義字體,省去了重複設置的麻煩。

方式二:加載系統字體

如果想直接引用系統字體,注意路徑需要以 /system 開頭:

Typeface tf = Typeface.createFromFile("/system/fonts/AndroidClock.ttf");

以上兩種方式都能實現自定義的 TextView 文本樣式。實際使用時,記得把字體文件命名規範化,並注意不同系統版本對字體路徑的兼容性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved