set custom font through xml

后端 未结 5 1742
忘掉有多难
忘掉有多难 2021-01-07 09:17

how can i set a font, whose ttf resides in my assets folder through xml? I know how to do that programmatically but how can you do that via xml? Thanks in adva

5条回答
  •  生来不讨喜
    2021-01-07 09:59

    You cannot do it using XML directly, however you can extend TextView and set a default font.

    package com.nannu;
    
    import android.content.Context;
    import android.graphics.Typeface;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class NanTV extends TextView{
    
        private Context c;
        public NanTV(Context c) {
            super(c);
            this.c = c;
            Typeface tfs = Typeface.createFromAsset(c.getAssets(),
                    "font/yourfont.ttf");
            setTypeface(tfs);
    
        }
        public NanTV(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            this.c = context;
            Typeface tfs = Typeface.createFromAsset(c.getAssets(),
                    "font/yourfont.ttf");
            setTypeface(tfs);
            // TODO Auto-generated constructor stub
        }
    
        public NanTV(Context context, AttributeSet attrs) {
            super(context, attrs);
            this.c = context;
            Typeface tfs = Typeface.createFromAsset(c.getAssets(),
                    "font/yourfont.ttf");
            setTypeface(tfs);
    
        }
    
    
    }
    

    And in your layout use new TextView

    
    

    I am posting this from my prev answer https://stackoverflow.com/a/11239305/1166537

提交回复
热议问题