編輯:關於 Android 程式設計
要讓 App 整體換上自訂字型,實務上常見四種做法,從最底層的反射替換,到最直觀的自訂 View,各有適用場景與風險。
Typeface 類別內部用幾個 static 欄位快取系統字型。透過反射把它們換掉,全 App 的文字都會跟著變。
public final class FontsOverride {
public static void setDefaultFont(Context context, String staticTypefaceFieldName,
String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) {
try {
final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
接著在自訂的 Application 裡執行替換:
public final class App extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
}
}
這個做法很誘人,但它依賴 Typeface 的內部實作細節,不同 Android 版本欄位名稱可能改變,升級系統後有機會失效,因此不建議用在需要長期維護的專案上。
最省力的方式,但只能從系統內建字型中挑選。
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:typeface">monospace</item>
</style>
從根 View 開始遞迴往下找,遇到 TextView 就套字型;若子 View 是自訂控件且有 setTypeface 方法,也能用反射處理。
/**
* 遞迴地為 ViewGroup 底下所有 TextView 設定字型
*/
public static final void setAppFont(ViewGroup mContainer, Typeface mFont, boolean reflect) {
if (mContainer == null || mFont == null) return;
final int mCount = mContainer.getChildCount();
for (int i = 0; i < mCount; ++i) {
final View mChild = mContainer.getChildAt(i);
if (mChild instanceof TextView) {
((TextView) mChild).setTypeface(mFont);
} else if (mChild instanceof ViewGroup) {
setAppFont((ViewGroup) mChild, mFont, reflect);
} else if (reflect) {
try {
Method mSetTypeface = mChild.getClass().getMethod("setTypeface", Typeface.class);
mSetTypeface.invoke(mChild, mFont);
} catch (Exception e) {
// 忽略不支援的控件
}
}
}
}
呼叫方式:
final Typeface mFont = Typeface.createFromAsset(getAssets(), "fonts/MyFont.ttf"); final ViewGroup mContainer = (ViewGroup) findViewById(android.R.id.content).getRootView(); setAppFont(mContainer, mFont, true);
注意:這個方法只對當下的 View 樹有效。RecyclerView 或 ListView 捲動後新建立的 item 不會被套用,因此更適合搭配方案四使用。
寫一個繼承 TextView 的子類別,在 init 裡指定字型,之後版面檔直接換標籤名稱即可。
public class CusFntTextView extends TextView {
public CusFntTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CusFntTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CusFntTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");
setTypeface(tf);
}
}
}
<com.packagename.CusFntTextView
android:id="@+id/tvtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hi Android"
android:textAppearance="?android:attr/textAppearanceLarge" />
需要快速驗證視覺效果,用方案二;頁面數量不多且結構固定,方案三最省事;長期維護的專案,方案四最穩,雖然要改版面檔,但行為可預期、可除錯。另外別忘了 isInEditMode() 的判斷,否則 Layout Editor 預覽會因為找不到字型而當掉。
Android 記憶體洩漏的常見成因總結
Java 是一種具備垃圾回收機制的語言,它的優點在於開發者無需特別管理記憶體配置,既降低了應用因局部故障(segmentation fault)而崩潰的風險,也避免了未釋
Android 源碼解析:View 的 Touch 事件分發機制
Touch 事件分發是 Android 面試與實戰中的高頻考點,網上解析文章也很多。本文的側重在於「用實驗現象反推源碼」——先動手跑出日誌順序,再回到原始碼中找出支撐這些
Android 入門:跑通第一個 OpenCV 程式
剛接觸 Android 開發時,由於先前對 OpenCV 較為熟悉,於是便想先在 Android 上把 OpenCV 跑起來。本文記錄了從環境配置到實現攝像頭即時影像處理
Android 自定義 View 實戰:打造圓形進度條風格的下載按鈕
需求是這樣來的 同事問怎麼做一個「按鈕形式的進度條」,下載中顯示進度,未開始時中間是個播放三角形,進行中則變成兩條暫停線。外圈的圓形進度其實已經有現成做法,真正要處理的是