2011-01-21 87 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方法并再次设置自定义字体。