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?
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);
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
Create a 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:
Right-click the font folder and go to New > Font resource file. The
New Resource File window appears.
Enter the file name, and then click OK. The new font resource XML
opens in the editor.
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 Spinners or ListViews (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:
add font you wish to use to your project as asset.
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
}
}
}
}
}
Related
How to set google font programmatically in Android
App is crash Caused by:
android.content.res.Resources$NotFoundException: Font resource ID
#0x7f090002 could not be retrieved.
val typeface = ResourcesCompat.getFont(applicationContext, R.font.halant)
appVersionName.typeface = typeface
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:app="http://schemas.android.com/apk/res-auto"
app:fontProviderAuthority="com.google.android.gms.fonts"
app:fontProviderPackage="com.google.android.gms"
app:fontProviderQuery="Halant"
app:fontProviderCerts="#array/com_google_android_gms_fonts_certs">
</font-family>
Though above two answers are correct, I will give you step-by-step details about "Downloadable Fonts" so that other will understand.
Note: A device must have Google Play services version 11 or higher to
use the Google Fonts provider.
In the Layout Editor, select a TextView, and then under Properties, select fontFamily > More Fonts.
Select the font want and make sure you choose create downloadable font (creates xml file in your font folder) and click OK.
Android Studio automatically generates the relevant XML files that are
needed to render the font correctly in your app.
Now, you can directly add it in TextView like this:
android:fontFamily="#font/halant_light"
Or use Downloadable Fonts programmatically like this:
val request = FontRequest(
"com.google.android.gms.fonts",
"com.google.android.gms",
"Halant", //your font
R.array.com_google_android_gms_fonts_certs
)
val callback = object : FontsContract.FontRequestCallback() {
override fun onTypefaceRetrieved(typeface: Typeface) {
// Your code to set the font goes here
}
override fun onTypefaceRequestFailed(reason: Int) {
// Your code to deal with the failure goes here
}
}
FontsContractCompat.requestFont(mContext, request, callback, mHandler)
If you don't want the above programmatic way you can use the below code which I tested and working perfectly:
val typeface = ResourcesCompat.getFont(applicationContext, R.font.halant_light)
fontText.typeface = typeface
val typeface = Typeface.create("sans-serif-condensed", Typeface.BOLD)
textView.typeface = typeface
I am using google downloadable fonts as given in below link
https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts.html
I want to use Montserrat font style semi bold but that option is not there in android
Also in below link there is style semibold any idea how to do it
https://fonts.google.com/specimen/Montserrat
following is my textview xml after adding font family
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:fontFamily="#font/montserrat"
android:text="#string/address"
android:textAllCaps="false"
android:textColor="#color/title_light_color"
android:textSize="10sp"
android:textStyle="bold" />
You can download here all types of fonts montserrat
https://github.com/google/fonts/tree/master/ofl/montserrat
https://github.com/google/fonts/blob/master/ofl/montserrat/Montserrat-SemiBold.ttf
Add in your res/font folder use this
android:fontFamily="#font/Montserrat-SemiBold"
Hope it helps
You can create a new font in res/font:
<?xml version="1.0" encoding="utf-8"?>
<font-family
xmlns:app="http://schemas.android.com/apk/res-auto"
app:fontProviderAuthority="com.google.android.gms.fonts"
app:fontProviderPackage="com.google.android.gms"
app:fontProviderQuery="name=Montserrat&weight=600"
app:fontProviderCerts="#array/com_google_android_gms_fonts_certs">
</font-family>
You can specify any supported weight by changing weight inside app:fontProviderQuery (600 for semi-bold). Android Studio will raise a FontValidationWarning, but it will work nonetheless.
Source: Google Fonts API for Android documentation
Try this ,
Create Customize font style for android app,
first create assets folder then create inside that font then put your downloaded font(ex: Light.ttf)
enter link description here
Then add this line in activity
Typeface mycustomface1 = Typeface.createFromAsset(context.getAssets(), "fonts/Light.ttf");
then declare that textview
textview.setTypeface(mycustomface1);
Create a class named FontCache:
import android.content.Context;
import android.graphics.Typeface;
import java.util.Hashtable;
public class FontCache {
private static Hashtable<String, Typeface> fontCache = new Hashtable<>();
public static Typeface get(String name, Context context) {
Typeface tf = fontCache.get(name);
if (tf == null) {
try {
tf = Typeface.createFromAsset(context.getAssets(), name);
} catch(Exception e) {
return null;
}
fontCache.put(name, tf);
}
return tf;
}
}
Then put the below lines of code in your activity:
Typeface montserratFontType = FontCache.get("fonts/montserrat.ttf", MainActivity.this);
yourTextView.setTypeface(montserratFontType);
At last, create an assets folder inside your main folder then create a fonts folder inside the assets folder and put your montserrat.ttf file.
I was trying to use custom font in Android Studio as we did in Eclipse. But unfortunately could not figure out where to put the 'assets' folder!
Update 2021:
Create a folder named font inside the res folder and copy your font
All font names must be only: lowercase a-z, 0-9, or underscore.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/abc_font" />
For programmatic use:
textView.setTypeface(ResourcesCompat.getFont(context, R.font.abc_font))
For Android Studio 4.2+ there's even now a menu option:
Select File>New>Folder>Assets Folder
Click finish
Right click on assets and create a folder called fonts
Put your font file in assets > fonts
Use code below to change your textView's font
TextView textView = (TextView) findViewById(R.id.textView);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/yourfont.ttf");
textView.setTypeface(typeface);
There are many ways to set custom font family on field and I am using like that below.
To add fonts as resources, perform the following steps in the Android Studio:
1) Right-click the res folder and go to New > Android resource directory. The New Resource Directory window appears.
2) In the Resource type list, select font, and then click OK.
Note: The name of the resource directory must be font.
3) Add your font files in the font folder.
Add font in desired view in your xml file:
Note: But you required the following things for that:
Android Studio above to 3.0 canary.
Your Activity extends AppCompatActivity.
Update your Gradle file like that:
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildtoolsVersion above to 26 and minimum targetSdkVersion required 26
Add dependencies in build.gradle file:
classpath 'com.android.tools.build:gradle:3.0.0-beta4'
gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
I think instead of downloading .ttf file we can use Google fonts. It's very easy to implements. only you have to follow these steps.
step 1) Open layout.xml of your project and the select font family of text view in attributes (for reference screen shot is attached)
step 2) The in font family select More fonts.. option if your font is not there. then you will see a new window will open, there you can type your required font & select the desired font from that list i.e) Regular, Bold, Italic etc.. as shown in below image.
step 3) Then you will observe a font folder will be auto generated in /res folder having your selected fonts xml file.
Then you can directly use this font family in xml as
android:fontFamily="#font/josefin_sans_bold"
or pro grammatically you can achieve this by using
Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);
fontText.setTypeface(typeface);
Hello here we have a better way to apply fonts on EditTexts and TextViews on android at once and apply it in whole project.
First of All you need to make fonts folder. Here are Steps.
1: Go to the (project folder) Then app>src>main
2: Create folders named 'assets/fonts' into the main folder.
3: Put your fonts into the fonts folder. Here I Have 'MavenPro-Regular.ttf'
Here are the Steps for applying custom fonts on EditText and using this approach you can apply fonts on every input.
1 : Create a Class MyEditText (your preferred name ...)
2 : which extends EditText
3 : Apply your font
Here is code Example;
public class MyEditText extends EditText {
public MyEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyEditText(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/MavenPro-Regular.ttf");
setTypeface(tf);
}
}
}
And in Here is the code how to use it.
MyEditText editText = (MyEditText) findViewById(R.id.editText);
editText.setText("Hello");
Or in Your xml File
<MyEditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textColor="#fff"
android:textSize="16dp"
android:id="#+id/editText"
/>
With Support Library 26.0 (and Android O) fonts can be loaded from resource easily with:
Typeface typeface = ResourcesCompat.getFont(Context context, int fontResourceId)
Docs for the method.
More info can be found here.
I want to add my answer for Android-O and Android Studio 2.4
Create folder called font under res folder. Download the various fonts you wanted to add to your project example Google fonts
Inside your xml user font family
example :
<TextView
android:fontFamily="#font/indie_flower"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="#string/sample_text" />
3.If you want it to be in programmatic way use following code
Typeface typeface = getResources().getFont(R.font.indie_flower);
textView.setTypeface(typeface);
for more information follow the link to my blog post Font styles for Android with Android Studio 2.4
As per new feature available in Android O, font resources in XML is avilable as new feature.
To add fonts as resources, perform the following steps in the Android Studio:
1) Right-click the res folder and go to New > Android resource directory. The New Resource Directory window appears.
2) In the Resource type list, select font, and then click OK.
Note: The name of the resource directory must be font.
3) Add your font files in the font folder.
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.
eg. Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);
You can use easy & simple EasyFonts third party library to set variety of custom font to your TextView. By using this library you should not have to worry about downloading and adding fonts into the assets/fonts folder. Also about Typeface object creation. You will be free from creating asset folder too.
Simply:
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(EasyFonts.robotoThin(this));
There are many type of fonts provided by this library.
Create folder assets in Project -> app (or your app name) -> src -> main -> right click -> New -> Directory.
Then create a new directory inside assets called "fonts".
To assign the font to the textView:
TextView textView = (TextView) findViewById(R.id.your_textView);
final Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/your_font_name");
your_font_name includes font extension.
1st add font.ttf file on font Folder. Then Add this line in onCreate method
Typeface typeface = ResourcesCompat.getFont(getApplicationContext(), R.font.myfont);
mytextView.setTypeface(typeface);
And here is my xml
<TextView
android:id="#+id/idtext1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:gravity="center"
android:text="My Text"
android:textColor="#000"
android:textSize="10sp"
/>
To use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26. For more information on using the support library, refer to the Using the support library section.
To add fonts as resources, perform the following steps in the Android Studio:
Right-click the res folder and go to New > Android resource directory.
The New Resource Directory window appears.
In the Resource type list, select font, and then click OK.
Add your font files in the font folder.
Creating a font family
To create a font family, perform the following steps in the Android Studio:
Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
Enter the file name, and then click OK. The new font resource XML opens in the editor.
Enclose each font file, style, and weight attribute in the element. The following XML illustrates adding font-related attributes in the font resource XML:
If your minSdkVersion is API level 26 and higher
<?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>
and if your minSdkVersion is lower than API level 26
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
<font
app:font="#font/lobster_italic"
app:fontStyle="normal"
app:fontWeight="400" />
</font-family>
Then you can use it any where like this
android:fontFamily="#font/your_custom_font_file"
Adding font to your project
To add fonts as resources, perform the following steps in the Android Studio:
1 - Right-click the res folder and go to New > Android resource directory.
The New Resource Directory window appears.
2 - In the Resource type list, select font, and then click OK.
3 - Add your font files in the font folder just by a simple copy and paste. note that the name of the fonts should be in lowercase.
Using fonts in XML layouts
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/lobster"/>
Adding fonts to style
<style name="customfontstyle" parent="#android:style/TextAppearance.Small">
<item name="android:fontFamily">#font/lobster</item>
</style>
Using fonts programmatically
Kotlin:
val typeface = resources.getFont(R.font.myfont)
textView.typeface = typeface
JAVA:
Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);
If you are very new to Android like I am this can be a little tricky. Make sure you call:
TextView myTextView = (TextView) findViewById(R.id.textView);
Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/your font.ttf");
myTextView.setTypeface(typeface);
method within a method such as onCreate.
Android 8.0 (API 26) introduced new features related to fonts.
1) Fonts can be used as resources.
2) Downloadable fonts.
If you want to use external fonts in your android application, you can either include font files in apk or configure downloadable fonts.
Including font files in APK : You can download font files, save them in res/font filer, define font family and use font family in styles.
For more details on using custom fonts as resources see http://www.zoftino.com/android-using-custom-fonts
Configuring downloadable fonts : Define font by providing font provider details, add font provider certificate and use font in styles.
For more details on downloadable fonts see http://www.zoftino.com/downloading-fonts-android
I could not load fonts because I had named my font file Poppins-Medium.tff, renaming it to poppins_medium.tff worked for me.
Rest of the steps remained the same:
Create the font resource directory under res folder
Copy and paste your tff file in that directory
Then use in TextView in XML using fontFamily attribute.
If above steps dont work, you can create a FontFamily of that font using this link
First create assets folder then create fonts folder in it.
Then you can set font from assets or directory like bellow :
public class FontSampler extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.custom);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
File font = new File(Environment.getExternalStorageDirectory(), "MgOpenCosmeticaBold.ttf");
if (font.exists()) {
tv = (TextView) findViewById(R.id.file);
face = Typeface.createFromFile(font);
tv.setTypeface(face);
} else {
findViewById(R.id.filerow).setVisibility(View.GONE);
}
}
}
Add your fonts to assets folder in app/src/main/assets
make a custom textview like this :
class CustomLightTextView : TextView {
constructor(context: Context) : super(context){
attachFont(context)
}
constructor(context: Context, attrs: AttributeSet): super(context, attrs){
attachFont(context)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
attachFont(context)
}
fun attachFont(context: Context) {
this.setTypeface(FontCache.getInstance().getLightFont(context))
}
}
Add FontCache : So that you don't have to create typeface again and again like :
class FontCache private constructor(){
val fontMap = HashMap<String,Typeface>()
companion object {
private var mInstance : FontCache?=null
fun getInstance():FontCache = mInstance?: synchronized(this){
return mInstance?:FontCache().also { mInstance=it }
}
}
fun getLightFont(context: Context):Typeface?{
if(!fontMap.containsKey("light")){
Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf");
fontMap.put("light",Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf"))
}
return fontMap.get("light")
}
}
And you are done !
P.S.From android O, you can directly add fonts.
Now there are so many ways to apply font one of easiest way is like this,
1) Right-click the res folder
go to New > Android resource directory.
2) From Resource type list, select font, and then click OK.
3) Put your font files in the font folder.
put fonts in asset folder
then apply fontfamily:''your fonts
Kotlin Answer
If you need to use fonts in code side, you can use this function also it has version code control.
fun getFontJarvisWhite(): Typeface {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) resources.getFont(R.font.jarvis_white)
else context?.let { ResourcesCompat.getFont(it, R.font.jarvis_white) }!!
}
For new readers
You can use this library
Gloxey Custom Font Views
gradle dependency
dependencies{
compile 'io.gloxey.cfv:custom-font-views:1.0.2'
}
How to use?
Create folder assets -> fonts. Copy your fonts into fonts folder.
Use property app : font_name = "font_name_string" to apply font on view.
Example
<!--Font Names in srings.xml-->
<string name="aadhunik">aadhunik.ttf</string>
<string name="kung_fool">kungfool.ttf</string>
<string name="skrova">skrova.otf</string>
<string name="painting_in_the_sun_light">painting_in_the_sun_light.ttf</string>
<!--Include views in layout.xml-->
<io.gloxey.cfv.CFTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Aadhunik"
android:textColor="#ff00"
android:textSize="40sp"
app:font_name="#string/aadhunik" />
<io.gloxey.cfv.CFButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Kung Fool"
android:textColor="#154748"
app:font_name="#string/kung_fool" />
<io.gloxey.cfv.CFEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello world"
android:textSize="30sp"
app:font_name="#string/skrova" />
<io.gloxey.cfv.CFCheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Painting In The Sun Light"
android:textSize="30sp"
app:font_name="#string/painting_in_the_sun_light" />
My question is quite simple:
In every of my textview, I am currently using the attribute
android:fontFamily="sans-serif-light"
to provide a gorgeous look on post HC devices.
Unfortunately, this doesn't work with every widget and for my Spinners, I need to overwrite the Adapter.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//You can use the new tf here.
if(convertView == null || convertView.getTag() == null) {
// new view - populate
convertView = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
convertView.setTag(new Object());
}
CheckedTextView spinner_text=(CheckedTextView) convertView.findViewById(android.R.id.text1);
//Typeface should be set here...
return spinner_text;
}
}
So, is there a way to get exactly the same result by code?
PS: No, I don't want to put a typeface in asset folder, I just want to use system one.
It should be possible with setTypeface() and Typeface.create():
convertView.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
See Docs:
Create a typeface object given a family name, and option style
information. If null is passed for the name, then the "default" font
will be chosen. The resulting typeface object can be queried
(getStyle()) to discover what its "real" style characteristics are.
Note that excessively using Typeface.create() is bad for your memory, as stated in this comment. The suggested Hashtable is a good solution, but you have to modify it a little since you don't create your typeface from an asset.
Android 4.1 (API Level 16) and Support Library 26 and higher
If you are using res -> font folder, you can use like this
val typeface = ResourcesCompat.getFont(Context, R.font.YOUR_FONT)
TextView.setTypeface(typeface)
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 , you can refer more about default font in this Default font family
In my opinion there is still a way to apply system fonts programatically on TextView without having any memory issue and that is using textview.setTextAppearance method :
<style name="styleA">
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
<style name="styleB">
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
<item name="android:textColor">?android:attr/textColorTertiary</item>
</style>
if(condition){
textView.setTextAppearance(context,R.style.styleA);
}else{
textView.setTextAppearance(context,R.style.styleB);
}
Option 1 - API 26 and higher
// Jave
Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);
// Kotlin
val typeface = resources.getFont(R.font.myfont)
textView.typeface = typeface
Option 2 - API 16 and higher
// Java
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
// Kotlin
val typeface = ResourcesCompat.getFont(context, R.font.myfont)
Check the full expiation at Android Developers Guide.
It would be possible by using
setTypeface(Typeface tf, int style) method of TextView class.
spinner_text.setTypeface(Typeface.SANS_SERIF,Typeface.NORMAL);
I applied a custom font to a TextView, but it doesn't seems to change the typeface.
Here is my code:
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(myTypeface);
Can anyone please get me out of this issue?
On Mobiletuts+ there is very good tutorial on Text formatting for Android. Quick Tip: Customize Android Fonts
EDIT: Tested it myself now. Here is the solution. You can use a subfolder called fonts but it must go in the assets folder not the res folder. So
assets/fonts
Also make sure that the font ending I mean the ending of the font file itself is all lower case. In other words it should not be myFont.TTF but myfont.ttf this way must be in lower case
After trying most of the solutions described in this thread, I accidentally found Calligraphy (https://github.com/chrisjenx/Calligraphy) - a library by Christopher Jenkins that lets you easily add custom fonts to your app. The advantages of his lib comparing to approaches suggested here are:
you don't have to introduce your own overriden TextView component, you use the built-in TextView
you can easily include the library using gradle
The library doesn't limit your choice of fonts; you just add your preferred ones to the assets dir
you not only get custom text views — all the other text-based Android compontents will also be displayed using your custom font.
I know there are good answers already, but here's a fully working implementation.
Here's the custom text view:
package com.mycompany.myapp.widget;
/**
* Text view with a custom font.
* <p/>
* In the XML, use something like {#code customAttrs:customFont="roboto-thin"}. The list of fonts
* that are currently supported are defined in the enum {#link CustomFont}. Remember to also add
* {#code xmlns:customAttrs="http://schemas.android.com/apk/res-auto"} in the header.
*/
public class CustomFontTextView extends TextView {
private static final String sScheme =
"http://schemas.android.com/apk/res-auto";
private static final String sAttribute = "customFont";
static enum CustomFont {
ROBOTO_THIN("fonts/Roboto-Thin.ttf"),
ROBOTO_LIGHT("fonts/Roboto-Light.ttf");
private final String fileName;
CustomFont(String fileName) {
this.fileName = fileName;
}
static CustomFont fromString(String fontName) {
return CustomFont.valueOf(fontName.toUpperCase(Locale.US));
}
public Typeface asTypeface(Context context) {
return Typeface.createFromAsset(context.getAssets(), fileName);
}
}
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
if (isInEditMode()) {
return;
} else {
final String fontName = attrs.getAttributeValue(sScheme, sAttribute);
if (fontName == null) {
throw new IllegalArgumentException("You must provide \"" + sAttribute + "\" for your text view");
} else {
final Typeface customTypeface = CustomFont.fromString(fontName).asTypeface(context);
setTypeface(customTypeface);
}
}
}
}
Here's the custom attributes. This should go to your res/attrs.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFontTextView">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
And here's how you use it. I'll use a relative layout to wrap it and show the customAttr declaration, but it could obviously be whatever layout you already have.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:customAttrs="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mycompany.myapp.widget.CustomFontTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="foobar"
customAttrs:customFont="roboto_thin" />
</RelativeLayout>
I've successfully used this before. The only difference between our implementations is that I wasn't using a subfolder in assets. Not sure if that will change anything, though.
Provided that you placed the font in the right place and there is no error in the font file itself, your code should work like that, RATTLESNAKE.
However, it would be a lot easier if you could just define a font in your layout xml, like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!-- This text view is styled with the app theme -->
<com.innovattic.font.FontTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This uses my font in bold italic style" />
<!-- This text view is styled here and overrides the app theme -->
<com.innovattic.font.FontTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:flFont="anotherFont"
android:textStyle="normal"
android:text="This uses another font in normal style" />
<!-- This text view is styled with a style and overrides the app theme -->
<com.innovattic.font.FontTextView
style="#style/StylishFont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This also uses another font in normal style" />
</LinearLayout>
With the accompanying res/values/styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<!-- Application theme -->
<!-- Use a different parent if you don't want Holo Light -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:textViewStyle">#style/MyTextViewStyle</item>
</style>
<!-- Style to use for ALL text views (including FontTextView) -->
<!-- Use a different parent if you don't want Holo Light -->
<style name="MyTextViewStyle" parent="#android:style/Widget.Holo.Light.TextView">
<item name="android:textAppearance">#style/MyTextAppearance</item>
</style>
<!-- Text appearance to use for ALL text views (including FontTextView) -->
<!-- Use a different parent if you don't want Holo Light -->
<style name="MyTextAppearance" parent="#android:style/TextAppearance.Holo">
<!-- Alternatively, reference this font with the name "aspergit" -->
<!-- Note that only our own TextView's will use the font attribute -->
<item name="flFont">someFont</item>
<item name="android:textStyle">bold|italic</item>
</style>
<!-- Alternative style, maybe for some other widget -->
<style name="StylishFont">
<item name="flFont">anotherFont</item>
<item name="android:textStyle">normal</item>
</style>
</resources>
I created a couple of tools specifically for this purpose. Refer to this project from GitHub, or take a look at this blog post which explains the whole thing.
The best way to do it From Android O preview release is this way:
It works only if you have android studio-2.4 or above
Right-click the res folder and go to New > Android resource directory. The New
Resource Directory window appears.
In the Resource type list, select font, and then click OK.
Add your font files in the font folder.The folder structure below generates R.font.dancing_script, R.font.la_la, and R.font.ba_ba.
Double-click a font file to preview the file's fonts in the editor.
Next we must create a font family:
Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
Enter the File Name, and then click OK. The new font resource XML opens in the editor.
Enclose each font file, style, and weight attribute in the font tag element. The following XML illustrates adding font-related attributes in the font resource XML:
Adding fonts to a TextView:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/hey_fontfamily"/>
As from the documentation
Working With Fonts
All the steps are correct.
For Custom Fonts in android create a folder within assets folder name it "fonts" place your desired fonts.ttf or .otf file in it.
If you extends UIBaseFragment:
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Arial.ttf");
tv.setTypeface(font);
else if extends Activity:
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/Arial.ttf");
tv.setTypeface(font);
You can use PixlUI at https://github.com/neopixl/PixlUI
import their .jar and use it in XML
<com.neopixl.pixlui.components.textview.TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
pixlui:typeface="GearedSlab.ttf" />
Since I was not satisfied with all the presented solutions on SO, I've come up with mine. It's based on a little trick with tags (i.e. you can't use tags in your code), I put the font path there. So when defining views, you can do either this:
<TextView
android:id="#+id/textViewHello1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World 1"
android:tag="fonts/Oswald-Regular.ttf"/>
or this:
<TextView
android:id="#+id/textViewHello2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World 2"
style="#style/OswaldTextAppearance"/>
<style name="OswaldTextAppearance">
<item name="android:tag">fonts/Oswald-Regular.ttf</item>
<item name="android:textColor">#000000</item>
</style>
Now you can either explicitly access / setup the view as:
TextView textView = TextViewHelper.setupTextView(this, R.id.textViewHello1).setText("blah");
or just setup everything via:
TextViewHelper.setupTextViews(this, (ViewGroup) findViewById(R.id.parentLayout)); // parentLayout is the root view group (relative layout in my case)
And what is the magic class you ask? Mostly glued from another SO posts, with helper methods for both activity and fragments:
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
public class TextViewHelper {
private static final Map<String, Typeface> mFontCache = new HashMap<>();
private static Typeface getTypeface(Context context, String fontPath) {
Typeface typeface;
if (mFontCache.containsKey(fontPath)) {
typeface = mFontCache.get(fontPath);
} else {
typeface = Typeface.createFromAsset(context.getAssets(), fontPath);
mFontCache.put(fontPath, typeface);
}
return typeface;
}
public static void setupTextViews(Context context, ViewGroup parent) {
for (int i = parent.getChildCount() - 1; i >= 0; i--) {
final View child = parent.getChildAt(i);
if (child instanceof ViewGroup) {
setupTextViews(context, (ViewGroup) child);
} else {
if (child != null) {
TextViewHelper.setupTextView(context, child);
}
}
}
}
public static void setupTextView(Context context, View view) {
if (view instanceof TextView) {
if (view.getTag() != null) // also inherited from TextView's style
{
TextView textView = (TextView) view;
String fontPath = (String) textView.getTag();
Typeface typeface = getTypeface(context, fontPath);
if (typeface != null) {
textView.setTypeface(typeface);
}
}
}
}
public static TextView setupTextView(View rootView, int id) {
TextView textView = (TextView) rootView.findViewById(id);
setupTextView(rootView.getContext().getApplicationContext(), textView);
return textView;
}
public static TextView setupTextView(Activity activity, int id) {
TextView textView = (TextView) activity.findViewById(id);
setupTextView(activity.getApplicationContext(), textView);
return textView;
}
}
Unfortunately there is no good solution for this.
I've seen the many articles about using a custom TextView but what they forget it that it's not only textviews that can implement fonts & there are textviews hidden away in other views inaccessible to the developer; I'm not even going to get started on Spannable.
You could use an external font utility like:
Calligraphy Font Tool
BUT This loops over every view in the application on it's creation and even this utility misses some views (ViewPager renders normal font) then you have the problem that is when Google updates their build tools this will occasionally crash because it needs to target deprecated properties. It's also a little slow as it uses Java's Reflection.
It's really up to Google to fix this. We need better font support in Android. If you look at the solution from iOS they literally have 100's of fonts built in to select from. Want a custom font? Simply drop a TFF in and it's usable..
For now were now limited to the offering that Google offers us which is extremely limited but fortunately mobile optimized.
Make sure to paste the above code into onCreate() after your call to the super and the call to setContentView(). This small detail kept my hung up for awhile.
With Android 8.0 using Custom Fonts in Application became easy with downloadable fonts.
We can add fonts directly to the res/font/ folder in the project folder, and in doing so, the fonts become automatically available in Android Studio.
Now set fontFamily attribute to list of fonts or click on more and select font of your choice. This will add tools:fontFamily="#font/your_font_file" line to your TextView.
This will Automatically generate few files.
1. In values folder it will create fonts_certs.xml.
2. In Manifest it will add this lines:
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
3.
preloaded_fonts.xml
<resources>
<array name="preloaded_fonts" translatable="false">
<item>#font/open_sans_regular</item>
<item>#font/open_sans_semibold</item>
</array>
</resources>
You can use easy & simple EasyFonts third party library to set variety of custom fonts to your TextView. By using this library you should not have to worry about downloading and adding fonts into the assets/fonts folder. Also about Typeface object creation.
Instead of
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(myTypeface);
Simply:
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(EasyFonts.robotoThin(this));
This library also provides following font face.
Roboto
Droid Serif
Droid Robot
Freedom
Fun Raiser
Android Nation
Green Avocado
Recognition
I had the same problem, the TTF did not show up. I changed the font file, and with the same code it's working.
If you want to load the font from the network or easily style it, you can use:
https://github.com/shellum/fontView
Example:
<!--Layout-->
<com.finalhack.fontview.FontView
android:id="#+id/someFontIcon"
android:layout_width="80dp"
android:layout_height="80dp" />
//Java:
fontView.setupFont("http://blah.com/myfont.ttf", true, character, FontView.ImageType.CIRCLE);
fontView.addForegroundColor(Color.RED);
fontView.addBackgroundColor(Color.WHITE);
Well, after seven years you can change whole app textView or what you want easily by using android.support libraries 26++.
E.g:
Create your font package app/src/res/font and move your font into it.
And in your app theme just add it as a fontFamily:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
. . . ...
<item name="android:fontFamily">#font/demo</item>
</style>
Example for use with textView only:
<style name="fontTextView" parent="#android:style/Widget.TextView">
<item name="android:fontFamily">monospace</item>
</style>
And add into your main theme:
<item name="android:textViewStyle">#style/fontTextView</item>
Currently it's worked on 8.1 until 4.1 API Jelly Bean And that's a wide range.
Update answer:
Android 8.0 (API level 26) introduces a new feature, Fonts in XML.
just use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26.
see this link
Old answer
There are two ways to customize fonts :
!!! my custom font in
assets/fonts/iran_sans.ttf
Way 1 :
Refrection Typeface.class ||| best way
call FontsOverride.setDefaultFont() in class extends Application, This code will cause all software fonts to be changed, even Toasts fonts
AppController.java
public class AppController extends Application {
#Override
public void onCreate() {
super.onCreate();
//Initial Font
FontsOverride.setDefaultFont(getApplicationContext(), "MONOSPACE", "fonts/iran_sans.ttf");
}
}
FontsOverride.java
public class FontsOverride {
public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
private static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) {
try {
final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Way 2: use setTypeface
for special view just call setTypeface() to change font.
CTextView.java
public class CTextView extends TextView {
public CTextView(Context context) {
super(context);
init(context,null);
}
public CTextView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public CTextView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CTextView(Context context, #Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context,attrs);
}
public void init(Context context, #Nullable AttributeSet attrs) {
if (isInEditMode())
return;
// use setTypeface for change font this view
setTypeface(FontUtils.getTypeface("fonts/iran_sans.ttf"));
}
}
FontUtils.java
public class FontUtils {
private static Hashtable<String, Typeface> fontCache = new Hashtable<>();
public static Typeface getTypeface(String fontName) {
Typeface tf = fontCache.get(fontName);
if (tf == null) {
try {
tf = Typeface.createFromAsset(AppController.getInstance().getApplicationContext().getAssets(), fontName);
} catch (Exception e) {
e.printStackTrace();
return null;
}
fontCache.put(fontName, tf);
}
return tf;
}
}
The correct way of doing this as of API 26 is described in the official documentation here :
https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html
This involves placing the ttf files in res/font folder and creating a font-family file.
The most simple solution android supported now!
Use custom font in xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/[your font resource]"/>
look details:
https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html
Open your project and select Project on the top left
app --> src --> main
right click to main and create directory name it as assets
right click to assest and create new directory name it fonts
you need to find free fonts like free fonts
give it to your Textview and call it in your Activity class
copy your fonts inside the fonts folder
TextView txt = (TextView) findViewById(R.id.txt_act_spalsh_welcome);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Aramis Italic.ttf");
txt.setTypeface(font);
name of the font must be correct and have fun
Yes, downloadable fonts are so easy, as Dipali s said.
This is how you do it...
Place a TextView.
In the properties pane, select the fontFamily dropdown. If it isn't there, find the caret thingy (the > and click on it to expand textAppearance) under the.
Expand the font-family drop down.
In the little list, scroll all the way down till you see more fonts
This will open up a dialog box where you can search from Google Fonts
Search for the font you like with the search bar at the top
Select your font.
Select the style of the font you like (i.e. bold, normal, italic, etc)
In the right pane, choose the radio button that says Add font to project
Click okay. Now your TextView has the font you like!
BONUS:
If you would like to style EVERYTHING with text in your application with chosen font, just add <item name="android:fontfamily">#font/fontnamehere</item> into your styles.xml