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

Android 字體設置全攻略:自定義 TTF 與 Roboto 字體用法

編輯:關於 Android 程式設計

一、自定義字體

1. 用 Typeface 加載 TTF 字體文件

如果系統自帶的字體滿足不了設計需求,我們可以把 ttf 字體文件打包進應用,再借助 Typeface 動態設置。整個過程分兩步:

第一步,在 assets 目錄下新建一個 fonts 文件夾,把 ttf 字體文件放進去。

第二步,在代碼中調用如下方法加載並應用:

AssetManager mgr = getAssets();               // 取得 AssetManager
Typeface tf = Typeface.createFromAsset(mgr, "fonts/ttf.ttf"); // 按路徑得到 Typeface
TextView tv = findViewById(R.id.textview);
tv.setTypeface(tf);                            // 套用字體

2. 讓中文也能「加粗」

在 XML 裡寫 android:textStyle="bold" 可以讓英文變成粗體,但這招對中文往往不奏效。想要給中文做出粗體效果,可以改用 TextPaint 的仿粗體設置:

TextView tv = (TextView) findViewById(R.id.TextView01);
tv.getPaint().setFakeBoldText(true); // 中文仿粗體:把 setFakeBoldText 設為 true
小提醒:部分字體對中文無效,這種情況不會報錯,但中文不會有任何變化,排查時要多加留意。

二、使用 Roboto 字體

從 Android 4.0 起,系統默認字體就換成了 Roboto。想在代碼裡調用它的不同字重,只需通過 android:fontFamily 指定即可:

android:fontFamily="sans-serif"             // Roboto Regular
android:fontFamily="sans-serif-light"       // Roboto Light
android:fontFamily="sans-serif-condensed"   // Roboto Condensed
android:fontFamily="sans-serif-thin"        // Roboto Thin(Android 4.2 起)
// 可與 android:textStyle="normal|bold|italic" 搭配使用

Roboto 家族提供的可用風格包括:

Regular、Italic、Bold、Bold-italic、Light、Light-italic、Thin、Thin-italic,以及 Condensed 系列下的 regular、italic、bold、bold-italic。

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