2011-01-21 89 views
1

我試圖實現使用我自己的自定義字體的自定義textview。使用自定義字體的自定義textview

有沒有一種方法來設置字體之前做一個Super.onDraw()?

以便將通常的字體替換爲我想要使用的自定義字體。

喜歡的東西:

protected void onDraw(Canvas canvas) 
{ 
    Typeface font1 = Typeface.createFromAsset(context.getAssets(), "fonts/myfonts.ttf"); 
    this.setTypeface(font1); 
    this.setTextSize(18); 
    super.onDraw(canvas); 
} 

我知道上面的代碼將無法正常工作。或者我不得不使用drawText()來做到這一點嗎?

回答

1

哦,我的不好,它確實改變了字體。

只是它沒有顯示在Eclipse上的預覽,但它確實顯示在模擬器上。

問題解決。

9

在每次調用onDraw方法時創建新的字體對象是非常糟糕的做法。字體設置之類的事情應該在類的構造函數中完成,而不是在每次繪製視圖時完成。

0
public class CustomTextView extends TextView { 

public CustomTextView(Context context, AttributeSet attributes) { 
    super(context, attributes); 
    applyCustomFont(context); 
} 

private void applyCustomFont(Context context) { 
    TypeFace customTypeFace = Typeface.createFromAsset(context.getAssets(), "custom_font_name"); 
    setTypeface(customTypeFace); 
} 

@Override 
public void setTextAppearance(Context context, int resid) { 
    super.setTextAppearance(context, resid); 
    applyCustomFont(context); 
} 
} 

的代碼片段創建一個自定義TextView和創建TextView的過程中它設置自定義字體。
當您嘗試以編程方式設置文本外觀時,自定義字體被重置。因此,您可以覆蓋setTextAppearance方法並再次設置自定義字體。