How to set custom font in .xml file instead of .java file?

前端 未结 8 470
無奈伤痛
無奈伤痛 2020-12-05 10:14

I am creating one Application in which I want to set custom font.

But I can\'t use custom Fonts in .xml file, for using this I need to initialize each and every Text

8条回答
  •  無奈伤痛
    2020-12-05 10:38

    You can simply use custom Text view like

    public class HelveticaRagularTextView extends TextView {
    
    public HelveticaRagularTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }
    
    public HelveticaRagularTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    
    }
    
    public HelveticaRagularTextView(Context context) {
        super(context);
        init(null);
    }
    
    private void init(AttributeSet attrs) {
        // Just Change your font name
        Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), getContext().getResources().getString(R.string.font_helvetica_regular));
        setTypeface(myTypeface);
    }
    

    }

    Now you can HelveticaRagularTextView in your xml.

    This is very easy to use

提交回复
热议问题