Question

I need to change the Roboto font for my app in XML and I want to change the Roboto font at RunTime. How do I do that?

Était-ce utile?

La solution

You use the assets file for this. Dump in your font in the assets file.

and using the Typeface class set font style accordingly.

Typeface style = Typeface.createFromAsset(asm, "fonts/Roboto-Bold.ttf");
view.setTypeFace(style);

Notice that here, Roboto font is saved inside another directory fonts inside assets.

For better practice, you can create a separate class which extends the Views that you need. Along with the package name, you can access the created view in the xml layout.

    public class BoldTextView extends TextView{

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


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


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

    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
            "fonts/Roboto-Bold.ttf");
        setTypeface(tf);
    }

}

Reference to this class in layout:

com.your.packagename.BoldTextView
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top