Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 字型設定與 Roboto 字型使用指南

編輯:Android 開發實例

本文整理 Android 上的字型設定方式,包含載入自訂 TTF 字型、讓中文呈現粗體效果,以及系統內建 Roboto 字型的用法。

一、使用自訂字型

以 TTF 檔設定 Typeface

可以先把 ttf 字型檔放進 assets,再在程式碼中建立 Typeface 套用。

第一步,在 assets 目錄下新增 fonts 資料夾,把 ttf 檔放進去。

第二步,在程式中載入並套用:

AssetManager mgr = getAssets();// 取得 AssetManager
Typeface tf = Typeface.createFromAsset(mgr, "fonts/ttf.ttf");// 依路徑取得 Typeface
tv = findViewById(R.id.textview);
tv.setTypeface(tf);// 設定字型

讓中文變粗體

在 XML 中使用 android:textStyle="bold" 可以讓英文變粗體,但對中文無效。中文要達到視覺上的粗體效果,得靠 TextPaint 的模擬粗體:

TextView tv = (TextView)findViewById(R.id.TextView01);
tv.getPaint().setFakeBoldText(true);// 中文模擬粗體

注意:部分字型套用後中文不會有任何變化,而且不會報錯,測試時容易漏掉。

二、使用 Roboto

從 Android 4.0 起,系統預設字型改為 Roboto。在 XML 中透過 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

可搭配的字重選項如下:

  • Regular
  • Italic
  • Bold
  • Bold-italic
  • Light
  • Light-italic
  • Thin
  • Thin-italic
  • Condensed regular
  • Condensed italic
  • Condensed bold
  • Condensed bold-italic

若需要更細緻的控制(例如 Medium、Black 字重), Roboto 家族在 5.0 之後可以透過字型家族 XML 精確指定,不必再依賴 fontFamily 的別名寫法。

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