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?
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?
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 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);
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);
you can use your font which you have store in font "res/font" ex. for API level 16 and above.
Typeface typeface = ResourcesCompat.getFont(context, R.font.rubik_medium);
txtView.setTypeface(typeface);
you can also use
Typeface typeface = getResources().getFont(R.font.rubik_medium);
txtView.setTypeface(typeface);
but it support with API level 26 and above.
With introduction of Fonts in XML in Android 8.0 (backward compatible from API version 14) its very easy to set font from xml itself.
From the android documentation:
Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in your R file and are automatically available in Android Studio. You can access the font resources with the help of a new resource type, font. For example, to access a font resource, use @font/myfont, or R.font.myfont.
Firstly create a Android Resource Directory in res
folder named as font
Add your .ttf font file to that directory, and then create font family
A font family is a set of font files along with its style and weight details. In Android, you can create a new font family as an XML resource and access it as a single unit, instead of referencing each style and weight as separate resources. By doing this, the system can select the correct font based on the text style you are trying to use.
To create a font family, perform the following steps in the Android Studio:
Enclose each font file, style, and weight attribute in the <font>
element. The following XML illustrates adding font-related
attributes in the font resource XML:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="@font/lobster_regular" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="@font/lobster_italic" />
</font-family>
Then use the following code to set font in your textView
like
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/lobster"/>
Here is a small utility class
public class TypefaceHelper {
public static void setViewGroupTypeface(ViewGroup container, Typeface typeface) {
final int children = container.getChildCount();
for (int i = 0; i < children; i++)
View child = container.getChildAt(i);
if (child instanceof TextView) {
setTextViewTypeface((TextView) child, typeface);
} else if (child instanceof ViewGroup) {
setViewGroupTypeface((ViewGroup) child, typeface);
}
}
}
public static void setTextViewTypeface(TextView textView, Typeface typeface) {
textView.setTypeface(typeface);
}
}
For things like Spinner
s or ListView
s (i.e. any kind of AdapterView
) which generate their children from an adapter you will need to set the typeface of each item View
in the getView
(or similar) method of the adapter. This is because views may be created as needed and so setting the Typeface
in onCreate
won't work properly.
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
If you don't want to use typeface and fiddle around with the path to your font file (Which may crash your application if you put in an incorrect path), here's another way.
First create a style in your styles.xml
<style name="YourFont">
<item name="android:fontFamily">@font/your_font</item>
</style>
Then you can just add the style using
textView.setTextAppearance(context, R.style.YourFont);
You need to use Typeface:
create Typeface object using that font:
Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/MyFont.ttf");
set typeface to the object you'd like to customize:
TextView myTextView = (TextView)findViewById(R.id.my_text_view);
myTextView.setTypeface(myFont);
You can use the following code to set all your text to a specific font at runtime. Just call the setViewGroupFont
method at the end of your Activity onCreate
method or whenever you dynamically create new views:
private static final String FONT_NAME = "fonts/Roboto-Regular.ttf";
private static Typeface m_font = null;
public static Typeface getFont(Context p_context)
{
if (null == m_font && null != p_context)
{
m_font = Typeface.createFromAsset(p_context.getApplicationContext().getAssets(), FONT_NAME);
}
return m_font;
}
public static void setViewGroupFont(ViewGroup p_viewGroup)
{
if (null != p_viewGroup)
{
for (int currChildIndex = 0; currChildIndex < p_viewGroup.getChildCount(); currChildIndex++)
{
View currChildView = p_viewGroup.getChildAt(currChildIndex);
if (ViewGroup.class.isInstance(currChildView))
{
setViewGroupFont((ViewGroup) currChildView);
}
else
{
try
{
Method setTypefaceMethod = currChildView.getClass().getMethod("setTypeface", Typeface.class);
setTypefaceMethod.invoke(currChildView, getFont(p_viewGroup.getContext()));
}
catch (NoSuchMethodException ex)
{
// Do nothing
}
catch (Exception ex)
{
// Unexpected error setting font
}
}
}
}
}
TextView
or ViewGroup
–
Vector TextView
is not sufficient since you also want to set the font on buttons, radio groups, spinners... (In fact, any control that supports the setTypeface
method) - And this is why using reflection is the most general way to do that. If you only wish to set fonts of TextView
, you can avoid it but otherwise you'll need to check each and every widget type and cast accordingly. –
Beechnut Spinner
extends ViewGroup
, and Button
extends TextView
so as I said checking for it being an instance of TextView
or ViewGroup
is generally sufficient. –
Vector © 2022 - 2024 — McMap. All rights reserved.