Using custom font in android TextView using xml

前端 未结 10 1088
执念已碎
执念已碎 2020-11-29 17:02

I have added a custom font file to my assets/fonts folder. How do I use it from my XML?

I can use it from code as follows:

TextView text =          


        
10条回答
  •  悲哀的现实
    2020-11-29 17:36

    Create a fonts folder in assets and add all your required font's there.

    public class CustomTextView extends TextView {
        private static final String TAG = "TextView";
    
        public CustomTextView(Context context) {
            super(context);
        }
    
        public CustomTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            setCustomFont(context, attrs);
        }
    
        public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            setCustomFont(context, attrs);
        }
    
        private void setCustomFont(Context ctx, AttributeSet attrs) {
            TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
            String customFont = a.getString(R.styleable.CustomTextView_customFont);
            setCustomFont(ctx, customFont);
            a.recycle();
        }
    
        public boolean setCustomFont(Context ctx, String fontName) {
            Typeface typeface = null;
            try {
                if(fontName == null){
                    fontName = Constants.DEFAULT_FONT_NAME;
                }
                typeface = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + fontName);
            } catch (Exception e) {
                Log.e(TAG, "Unable to load typeface: "+e.getMessage());
                return false;
            }
            setTypeface(typeface);
            return true;
        }
    }
    

    and add a declarable in attrs.xml

    
          
    
    

    and then add your customFont like

    app:customFont="arial.ttf"
    

提交回复
热议问题