Android:更好的自訂字型方案

來源:互聯網
上載者:User

標籤:

http://ryanhoo.github.io/blog/2014/05/05/android-better-way-to-apply-custom-font/

  • 情景
  • 解決方案
    • 1)Android預設方法 #1
    • 2)Android預設方法 #2
    • 3)我的解決方案
  • 譯者注
  • 參考

原文:http://vision-apps.blogspot.hk/2012/02/android-better-way-to-apply-custom-font.html

在一個應用中,我需要在所有的UI組件中使用客戶提供的字型。這聽起來似乎是個很稀鬆平常的任務,不是嗎?是的,我當時也是這麼想的。然後我震驚了,Android竟然沒有提供一個簡單優雅的方式來做這件事情!

所以,在這篇文章中我會展示Android提供的預設方法,然後我會分享更加簡單優雅的解決方案。

情景

你需要為整個應用替換自訂字型。

解決方案1)Android預設方法 #1

你可以通過ID尋找到View,然後挨個為它們設定字型。在單個View的情況下,它看起來也沒有那麼可怕。

123
Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/YourCustomFont.ttf");TextView view = (TextView) findViewById(R.id.activity_main_header);view.setTypeface(customFont);

但是在很多TextView、Button等文本組件的情況下,我敢肯定你不會喜歡這個方法的。:D

2)Android預設方法 #2

你可以為每個文本組件建立一個子類,如TextView、Button等,然後在建構函式中載入自訂字型。

12345678910111213141516171819
public class BrandTextView extends TextView { public BrandTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public BrandTextView(Context context, AttributeSet attrs) { super(context, attrs); } public BrandTextView(Context context) { super(context); } public void setTypeface(Typeface tf, int style) { if (style == Typeface.BOLD) { super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/YourCustomFont_Bold.ttf")); } else { super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/YourCustomFont.ttf")); } } }

然後只需要將標準的文本控制項替換成你自訂的就可以了(例如BrandTextView替換TextView)。

123456789
<com.your.package.BrandTextView         android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View with custom font"/><com.your.package.BrandTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="View with custom font and bold typeface"/>

還有,你甚至可以直接在XML中添加自訂的字型屬性。要實現這個,你需要定義你自己的declare-styleable屬性,然後在組件的建構函式中解析它們。

為了不佔篇幅介紹這麼基礎的東西,這裡有一篇不錯的文章告訴你怎麼自訂控制項屬性。

http://kevindion.com/2011/01/custom-xml-attributes-for-android-widgets/

在大多數情況下,這個方法還不賴,並且有一些優點(例如,切換字型粗細等等,字型可以在組件xml檔案的typeface屬性中定義)。但是我認為這個實現方法還是太重量級了,並且依賴大量的模板代碼,為了一個替換字型的簡單任務,有點兒得不償失。

3)我的解決方案

理想的解決方案是自訂佈景主題,然後應用到全域或者某個Activity。 但不幸的是,Android的android:typeface屬性只能用來設定系統內嵌的字型,而非使用者自訂字型(例如assets檔案中的字型)。這就是為什麼我們無法避免在Java代碼中載入並設定字型。

所以我決定建立一個協助類,使得這個操作儘可能的簡單。使用方法:

1
FontHelper.applyFont(context, findViewById(R.id.activity_root), "fonts/YourCustomFont.ttf");

並且這行代碼會用來載入所有的基於TextView的文本組件(TextView、Button、RadioButton、ToggleButton等等),而無需考慮介面的布局層級如何。

這是怎麼做到的?非常簡單:

12345678910111213
public static void applyFont(final Context context, final View root, final String fontName) { try { if (root instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) root; for (int i = 0; i < viewGroup.getChildCount(); i++) applyFont(context, viewGroup.getChildAt(i), fontName); } else if (root instanceof TextView) ((TextView) root).setTypeface(Typeface.createFromAsset(context.getAssets(), fontName)); } catch (Exception e) { Log.e(TAG, String.format("Error occured when trying to apply %s font for %s view", fontName, root)); e.printStackTrace(); }}

正如你所看到的,所需要做的僅僅是將基於TextView的文本組件從布局中遍曆出來而已。

你可以在這裡下載到範例程式碼,裡面有FontHelper的具體用法。

譯者注

在多重專案中,我都碰到過類似的需求,早期採用的是第二種實現方法,但是缺點在於對於第三方組件,你需要去修改別人的代碼,才能實現自訂字型,這恰恰違反了OC(Open & Close)原則,對擴充開放,對修改封閉。

剛看到第三種的時候,也是驚為天人,姑且不說結果,我覺得這種活躍的思路非常重要,很值得學習參考。

但是最後被team裡的人否決了,理由是違背組件設計原則,實現方式略嫌粗暴。後來我仔細想想,一個是要做好記憶體管理(似乎會引起記憶體問題),檢視狀態改變,也要重複載入(橫豎屏、onResume等),也絕對不是簡單的活兒。

所以暫訂使用第一種方法,typeface使用單例,需要時設定字型。

我個人覺得第一種還是個體力活,而且到後來,這個代碼重複率還是非常高的,這又違背了DRY原則。

在地鐵上的時候,突然想到DI(Dependency Inject)。已經有一些DI的架構,如ButterKnife,那寫出來應該是這樣:

1
@CustomFont(R.id.textView) TextView textView

or

12
@InjectView(id=R.id.textView, customFont=true) View anyView@InjectView(id=R.id.textView, customFont=true, font="fonts/ltfz.ttf") View anyView

這樣寫出來代碼相比重複寫setTypeface要好一些。

目前我們的項目還沒有使用這類DI架構,等以後引入了,使用第二種注入,寫起來應該是很爽的。

保持更新。

參考
  • DI架構
  • ButterKnife

 

Android:更好的自訂字型方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.