Change font of entire application

866 views Asked by At

I want to use custom font in my application. Which is the best way to give font to entire application. I know how to assign custom font to a single TextView or Button.

Is it possible to mention the custom font in one place, for eg. in styles.xml, and the font will be applied to whole application (every TextView, Button, EditText and soon).

2

There are 2 answers

4
Naveen Tamrakar On BEST ANSWER

use this type of textview in your app

public class MyTextView extends TextView {

public MyTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public MyTextView(Context context) {
    super(context);
    init();
}

public void init() {
    Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/chiller.ttf");
    setTypeface(tf ,1);

}

}

also edit text

public class CEditText extends EditText {


private Context context;
private AttributeSet attrs;
private int defStyle;

public CEditText(Context context) {
    super(context);
    this.context=context;
    init();
} 

 public CEditText(Context context, AttributeSet attrs) {
      super(context, attrs);
      this.context=context;
      this.attrs=attrs;
      init();
 }

public CEditText(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      this.context=context;
      this.attrs=attrs;
      this.defStyle=defStyle;
      init();
}

private void init() {
      Typeface font=Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
      this.setTypeface(font);
}
@Override
public void setTypeface(Typeface tf, int style) {
    tf=Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
    super.setTypeface(tf, style);
}

@Override
public void setTypeface(Typeface tf) {
    tf=Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
    super.setTypeface(tf);
}
0
Rames Palanisamy On

Unfortunatly, android is not providing any method to apply custom font for the complete app in one place.

However, you can create your CustomTextView extends TextView and CustomButton extends Button. In that you can set the font by creating a FontInstance.