2011-12-07 79 views
4

有沒有辦法通過對TextView的自定義字體(或它的子類)僅使用XML,而不提供這樣自定義TrueType字體僅

Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/CustomFont.ttf"); 
+0

都能跟得上我不這麼認爲:( – ingsaurabh

+0

沒有,如果你想自定義字體使用,那麼你必須寫爲Java代碼。 – anddev

回答

5

這是不可能做到這一點任何Java代碼純粹來自XML,但你可以創建自定義視圖並從XML引用。這樣你只需要編寫一次代碼,就可以在各種佈局中回收它。

例如,聲明類FontTextView

package com.example; 

import android.content.Context; 
import android.util.AttributeSet; 
import android.widget.TextView; 

public class FontTextView extends TextView { 

    /** 
    * Note that when generating the class from code, you will need 
    * to call setCustomFont() manually. 
    */ 
    public FontTextView(Context context) { 
     super(context); 
    } 

    public FontTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setCustomFont(this, attrs); 
    } 

    public FontTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     setCustomFont(this, attrs); 
    } 

    private void setCustomFont(Context context, AttributeSet attrs) { 
     if (isInEditMode()) { 
      // Ignore if within Eclipse 
      return; 
     } 
     String font = "myDefaultFont.ttf"; 
     if (attrs != null) { 
      // Look up any layout-defined attributes 
      TypedArray a = obtainStyledAttributes(attrs, 
        R.styleable.FontTextView); 
      for (int i = 0; i < a.getIndexCount(); i++) { 
       int attr = a.getIndex(i); 
       switch (attr) { 
       case R.styleable.FontTextView_customFont: 
        font = a.getString(attr, 0); 
        break; 
       } 
      } 
      a.recycle(); 
     } 
     Typeface tf = null; 
     try { 
      tf = Typeface.createFromAsset(getAssets(), font); 
     } catch (Exception e) { 
      Log.e("Could not get typeface: " + e.getMessage()); 
     } 
     setTypeface(tf); 
    } 

} 

定義屬性在res/values/attrs.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <declare-styleable name="FontTextView"> 
     <attr name="customFont" format="string" /> 
    </declare-styleable> 

</resources> 

使用它的佈局:

  1. 聲明命名空間:

    xmlns:custom="http://schemas.android.com/apk/res/com.example" 
    
  2. 使用FontTextView

    <com.example.FontTextView 
        android:id="@+id/introduction" 
        customFont="myCustomFont.ttf" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Hello world!" /> 
    
+0

我很抱歉,但如果我想使用Button或CheckedTextView或CompountButton或其他我應該爲他們每個人做一個擴展?這不是一個很好的解決方案抱歉:-( –

+2

將'setCustomFont()'概括爲靜態上下文,如果您始終使用XML構造函數,則只需要爲每個視圖元素定義一個構造函數。只發現了五個左右不同的控件,我想擴展它們,並且由於您不需要任何額外的視圖或佈局代碼,我發現它是最好的解決方案。 –

+0

@s_id這是最好的解決方案,除了添加一些靜態緩存,所以你不必在每次創建一個新的FontTextView對象時加載字體.. – styler1972