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

Android 動態設定控件文字顏色與自訂字體的兩種方式

編輯:關於 Android 程式設計

做主題換色、自訂字型這類需求時,有兩件事經常一起出現:改文字顏色、換字型。下面把常用寫法整理出來。

一、用程式碼設定文字顏色

int b = getResources().getColor(R.drawable.blue);   // 從資源檔讀取顏色
mButton.setTextColor(b);

也可以直接用 android.graphics.Color 的常數,例如 Color.BLUE,不必先建立資源。

二、設定自訂字體的兩種方式

方式一:載入字型檔

mText.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf"));

這裡有三個必須注意的地方:

  1. 檔案一定要是 ttf 格式。
  2. 要放在 assets/fonts/ 目錄下。
  3. 找不到字型時不會報錯,只是執行時字體不會變——這是它最容易被誤判的地方,路徑打錯也一樣安靜。

方式二:使用系統內建樣式

fontButton.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC));

這招不需要任何檔案,直接套用系統支援的粗體、斜體等樣式。

三、完整示範程式碼

這個範例做了兩件事:點擊按鈕會依序切換文字的顏色;另一顆按鈕則負責套用自訂字型。

package com.oyzz.ch3_6;

/* 必須引用 graphics.Color 才能使用 Color.* 的對象 */
import android.graphics.Color;
import android.graphics.Typeface;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Ch3_6 extends Activity
{
    private Button mButton;
    private TextView mText;
    private int[] mColors;
    private int colornum;
    private Button fontButton;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mButton = (Button) findViewById(R.id.mybutton);
        mText = (TextView) findViewById(R.id.mytext);
        fontButton = (Button) findViewById(R.id.mybutton1);

        // 宣告並構造整數陣列來存放欲使用的文字顏色
        mColors = new int[]
            {
                Color.BLACK, Color.RED, Color.BLUE,
                Color.GREEN, Color.MAGENTA, Color.YELLOW
            };
        colornum = 0;

        // 得到 color.xml 檔案裡的顏色
        int b = getResources().getColor(R.drawable.blue);
        mButton.setTextColor(b);

        // 使用 setOnClickListener 讓按鈕聆聽事件
        mButton.setOnClickListener(new View.OnClickListener()
        {
            // 使用 onClick 讓用戶點下按鈕來驅動變動文字顏色
            public void onClick(View v)
            {
                if (colornum < mColors.length)
                {
                    mText.setTextColor(mColors[colornum]);
                    colornum++;
                }
                else
                {
                    colornum = 0;
                }
            }
        });

        fontButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                mText.setTypeface(Typeface.createFromAsset(getAssets(),
                        "fonts/HandmadeTypewriter.ttf"));   // 設置自訂字體
                fontButton.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC));
            }
        });
    }
}

四、版面檔 main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Layout 使用白色的背景 -->
<LinearLayout
    android:id="@+id/widget27"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/white"
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" >
    <!-- 文字使用 mytext 作為 id,採用 string.xml 中的 textview_str 參數,預設文字顏色為灰色 -->
    <TextView
    android:id="@+id/mytext"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/textview_str"
    android:textColor="@drawable/darkgray" >
    </TextView>
    <!-- 按鈕以 mybutton 作為 id,使用 string.xml 中的 button_str 參數 -->
    <Button
    android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_str" >
    </Button>
    <Button
    android:id="@+id/mybutton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="字體" >
    </Button>
</LinearLayout>

五、顏色資源 color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <drawable name="darkgray">#404040ff</drawable>
    <drawable name="black">#000</drawable>
    <drawable name="red">#ff00ff</drawable>
    <drawable name="green">#0ff0ff</drawable>
    <drawable name="lightgray">#c0c0c0ff</drawable>
    <drawable name="white">#ffffffff</drawable>
    <drawable name="yellow">#ffFF33ff</drawable>
    <drawable name="blue">#00ffff</drawable>
    <drawable name="gray">#808080ff</drawable>
    <drawable name="magenta">#ff6699ff</drawable>
    <drawable name="cyan">#66ffffff</drawable>
</resources>

六、字串資源 strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Ex03_13</string>
    <string name="app_name">Ex03_13</string>
    <string name="textview_str">轉吧七彩霓虹燈</string>
    <string name="button_str">按我</string>
</resources>

實務補充

幾個可以讓這類程式碼更乾淨的做法:顏色建議定義在 res/values/colors.xml 的 <color> 標籤而非 <drawable>,語意比較正確;getResources().getColor() 在新版 API 已標記為 deprecated,改用 ContextCompat.getColor(context, R.color.xxx);自訂字型若會重複載入,建議用靜態變數快取 Typeface 物件,因為每次 createFromAsset 都有可觀的 IO 成本。

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