-1

Given a Button created at runtime:

Button button = Button(context)

The way to set a custom typeface is:

button.setTypeface(myTypeface)

However I find it only works before I add it to a ViewGroup and not after.

I've also tried:

button.setTypeface(myTypeface, myStyle) 

but it didn't work either. I need to change my Button font dynamically. I've tried invalidate() and requestLayout() but the font never changes.

Barry Fruitman
  • 12,316
  • 13
  • 72
  • 135

1 Answers1

2

Solution:- you can subclass the Button class with your custom font and use it instead of button.

public class MyButton extends AppCompatButton {

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

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

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

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf");
            setTypeface(tf);
        }
    }
}