How to change the font on the TextView?

前端 未结 16 1054
清歌不尽
清歌不尽 2020-11-22 08:09

How to change the font in a TextView, as default it\'s shown up as Arial? How to change it to Helvetica?

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 08:38

    Best practice ever

    TextViewPlus.java:

    public class TextViewPlus extends TextView {
        private static final String TAG = "TextView";
    
        public TextViewPlus(Context context) {
            super(context);
        }
    
        public TextViewPlus(Context context, AttributeSet attrs) {
            super(context, attrs);
            setCustomFont(context, attrs);
        }
    
        public TextViewPlus(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.TextViewPlus);
            String customFont = a.getString(R.styleable.TextViewPlus_customFont);
            setCustomFont(ctx, customFont);
            a.recycle();
        }
    
        public boolean setCustomFont(Context ctx, String asset) {
            Typeface typeface = null;
            try {
                typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
            } catch (Exception e) {
                Log.e(TAG, "Unable to load typeface: "+e.getMessage());
                return false;
            }
    
            setTypeface(typeface);
            return true;
        }
    }
    

    attrs.xml: (Where to place res/values)

    
    
        
            
        
    
    

    How to use:

    
    
    
        
        
    
    

    Hope this will help you.

提交回复
热议问题