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

Android 正確使用 iconfont 字體圖標的完整做法

編輯:關於 Android 程式設計

什麼是字體圖標

字體圖標,也常被稱為 iconfont,是把圖示整理成字型檔,例如 .ttf,再透過文字方式顯示。和一般 PNG 圖片相比,字體圖標可以更靈活地調整大小與顏色。

常見的優點包括:

  • 可以自由改變大小與顏色。
  • 可減少多張圖片資源帶來的 APK 體積。
  • 在不同解析度下更容易保持清晰度。
  • 使用方式簡單,適合大量小型圖示。

缺點則是:

  • 不適合當作複雜背景圖或九宮格圖。
  • 部分圖示若需要文字說明,直接使用圖片會更合適。
  • 不同圖示可能存在邊距差異,切換時要注意視覺一致性。

基本使用步驟

1. 將字型檔放入 assets

把下載好的 iconfont 字型檔複製到 assets/iconfont/ 目錄。

2. 找到圖示對應的字符碼

開啟 iconfont 提供的 demo.html,找到要使用的圖示,並記下其 HTML 實體字符碼。

3. 在 strings.xml 中定義文字

<string name="icons">手機圖示字符碼</string>

4. 在 TextView 中套用

<TextView
    android:id="@+id/like"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/icons" />

5. 設定 Typeface

Typeface iconfont = Typeface.createFromAsset(
    getAssets(),
    "iconfont/iconfont.ttf"
);

TextView textView = findViewById(R.id.like);
textView.setTypeface(iconfont);

完成後畫面如下:

用自訂 TextView 簡化重複設定

如果多個頁面都要使用 iconfont,每次都呼叫 setTypeface 會產生不少重複程式碼。更好的做法是建立一個自訂 TextView,在初始化時自動套用字型。

public class IconFontTextview extends TextView {
    public IconFontTextview(Context context) {
        super(context);
        init(context);
    }

    public IconFontTextview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public IconFontTextview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        Typeface iconfont = Typeface.createFromAsset(
            context.getAssets(),
            "iconfont/iconfont.ttf"
        );
        setTypeface(iconfont);
    }
}

之後在布局中直接使用這個自訂元件即可:

<com.example.view.IconFontTextview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textColor="@android:color/holo_red_dark"
    android:text="手機圖示字符碼" />

透過 iconfont,開發者可以用文字方式管理圖示,讓介面中的小圖更靈活,也更容易統一調整風格。

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