Reputation: 238
I'm trying to implement a custom textview that uses my own custom font.
is there a way to set the typeface before doing a Super.onDraw()?
So as to replace the usual font to the custom font that I want to use.
Something like:
protected void onDraw(Canvas canvas)
{
Typeface font1 = Typeface.createFromAsset(context.getAssets(), "fonts/myfonts.ttf");
this.setTypeface(font1);
this.setTextSize(18);
super.onDraw(canvas);
}
I know the above code won't work.
Or do I have no choice but to use drawText() to do so?
Upvotes: 1
Views: 2819
Reputation: 2178
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);
}
}
The code snippet creates a custom TextView
and during the creation of the textview it set the custom font.
When you try to programmatically set the text appearance, the custom font is reset. Hence you can override the setTextAppearance
method and set the custom font again.
Upvotes: 0
Reputation: 91
It's a very bad practice to create new Typeface object on every time when your onDraw method is called. Such things as font set up should be done in the class constructor but not on every time your view is being drawn.
Upvotes: 9
Reputation: 238
Oh my bad, it actually does change the font.
Just that it didn't show up on the preview on Eclipse but it does show on the emulator.
Problem solved.
Upvotes: 1