How to change the font on the TextView?

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

    It's a little old, but I improved the class CustomFontLoader a little bit and I wanted to share it so it can be helpfull. Just create a new class with this code.

     import android.content.Context;
     import android.graphics.Typeface;
    
    public enum FontLoader {
    
    ARIAL("arial"),
    TIMES("times"),
    VERDANA("verdana"),
    TREBUCHET("trbuchet"),
    GEORGIA("georgia"),
    GENEVA("geneva"),
    SANS("sans"),
    COURIER("courier"),
    TAHOMA("tahoma"),
    LUCIDA("lucida");   
    
    
    private final String name;
    private Typeface typeFace;
    
    
    private FontLoader(final String name) {
        this.name = name;
    
        typeFace=null;  
    }
    
    public static Typeface getTypeFace(Context context,String name){
        try {
            FontLoader item=FontLoader.valueOf(name.toUpperCase(Locale.getDefault()));
            if(item.typeFace==null){                
                item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");                 
            }           
            return item.typeFace;
        } catch (Exception e) {         
            return null;
        }                   
    }
    public static Typeface getTypeFace(Context context,int id){
        FontLoader myArray[]= FontLoader.values();
        if(!(id

    Then just use this code on you textview:

     Typeface typeFace=FontLoader.getTypeFace(context,"arial");  
     if(typeFace!=null) myTextView.setTypeface(typeFace);
    

提交回复
热议问题