How to change the font on the TextView?

前端 未结 16 735
清歌不尽
清歌不尽 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:30

    1. add class FontTextView.java:


    public class FontTextView extends TextView {
        String fonts[] = {"HelveticaNeue.ttf", "HelveticaNeueLight.ttf", "motschcc.ttf", "symbol.ttf"};
    
        public FontTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init(attrs);
        }
    
        public FontTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            if (!isInEditMode()) {
                init(attrs);
            }
    
        }
    
        public FontTextView(Context context) {
            super(context);
            if (!isInEditMode()) {
                init(null);
            }
        }
    
        private void init(AttributeSet attrs) {
            if (attrs != null) {
                TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
                if (a.getString(R.styleable.FontTextView_font_type) != null) {
                    String fontName = fonts[Integer.valueOf(a.getString(R.styleable.FontTextView_font_type))];
    
                    if (fontName != null) {
                        Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/" + fontName);
                        setTypeface(myTypeface);
                    }
                    a.recycle();
                }
            }
        }
    }
    


    1. add to assets library font


    1. add to attrs.xml , The numbers should be in the order in array class.

      
      
          
          
          
          
      
      


    1. Select a font from the list

提交回复
热议问题