Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set font at runtime, TextView

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

I created a TextView

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

I can easily change the size, now I'd like to set font style to "Verdana".

How to do this?

like image 599
Shishir.bobby Avatar asked Aug 14 '10 11:08

Shishir.bobby


2 Answers

To set In-built Font at Run-Time:

  • First of all, To Change Font-face, a Typeface class is used.

  • Now, at Run-Time, to set the font-face, Use setTypeface(Typeface) from the Java code

  • at Design-Time, to set the font-face, Use android:typeface="serif"

For example:

<TextView android:text="@+id/TextView01"  android:id="@+id/TextView01"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:textSize="30px"  android:textStyle="italic"  android:typeface="serif" /> 

To set Custom font(s) in your Android application

To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets. You might, for example, create assets/fonts/ and put your TTF files in there:

  TextView tv=(TextView)findViewById(R.id.custom);    Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");    tv.setTypeface(face);  
like image 59
Paresh Mayani Avatar answered Sep 21 '22 04:09

Paresh Mayani


You can have .ttf font in your asset folder. Say font's name is "default.ttf" and you just now have to write below 2 lines of code

TextView text = new TextView(this); text.setTypeface(Typeface.createFromAsset(getAssets(), "default.ttf")); 

You must also we careful because different font have different sizes. You may need to set size as :

text.setTextSize(20); 
like image 26
Dilroop Singh Avatar answered Sep 22 '22 04:09

Dilroop Singh