Set font at runtime, TextView

前端 未结 9 675
温柔的废话
温柔的废话 2020-11-29 22:00

How to set the font of a TextView created at runtime?

I created a TextView

Textview tv = new TextView(this);      
tv.setTextSize(20);

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 22:12

    Dynamically you can set the fontfamily similar to android:fontFamily in xml by using this,

    For Custom font:
    
     TextView tv = ((TextView) v.findViewById(R.id.select_item_title));
     Typeface face=Typeface.createFromAsset(getAssets(),"fonts/mycustomfont.ttf"); 
     tv.setTypeface(face);
    
    For Default font:
    
     tv.setTypeface(Typeface.create("sans-serif-medium",Typeface.NORMAL));
    

    These are the list of default font family used, use any of this by replacing the double quotation string "sans-serif-medium"

    FONT FAMILY                    TTF FILE                    
    
    1  casual                      ComingSoon.ttf              
    2  cursive                     DancingScript-Regular.ttf   
    3  monospace                   DroidSansMono.ttf           
    4  sans-serif                  Roboto-Regular.ttf          
    5  sans-serif-black            Roboto-Black.ttf            
    6  sans-serif-condensed        RobotoCondensed-Regular.ttf 
    7  sans-serif-condensed-light  RobotoCondensed-Light.ttf   
    8  sans-serif-light            Roboto-Light.ttf            
    9  sans-serif-medium           Roboto-Medium.ttf           
    10  sans-serif-smallcaps       CarroisGothicSC-Regular.ttf 
    11  sans-serif-thin            Roboto-Thin.ttf             
    12  serif                      NotoSerif-Regular.ttf       
    13  serif-monospace            CutiveMono.ttf              
    

    "mycustomfont.ttf" is the ttf file. Path will be in src/assets/fonts/mycustomfont.ttf

提交回复
热议问题