Custom fonts and XML layouts (Android)

后端 未结 18 2201
执念已碎
执念已碎 2020-11-22 07:21

I\'m trying to define a GUI layout using XML files in Android. As far as I can find out, there is no way to specify that your widgets should use a custom font (e.g. one you\

18条回答
  •  旧巷少年郎
    2020-11-22 07:44

    If you only have one typeface you would like to add, and want less code to write, you can create a dedicated TextView for your specific font. See code below.

    package com.yourpackage;
    import android.content.Context;
    import android.graphics.Typeface;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class FontTextView extends TextView {
        public static Typeface FONT_NAME;
    
    
        public FontTextView(Context context) {
            super(context);
            if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
            this.setTypeface(FONT_NAME);
        }
        public FontTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
            this.setTypeface(FONT_NAME);
        }
        public FontTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
            this.setTypeface(FONT_NAME);
        }
    }
    

    In main.xml, you can now add your textView like this:

    
    

提交回复
热议问题