Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top