How to use custom font in android xml? [duplicate] - android

This question already has answers here:
Android: Want to set custom fonts for whole application not runtime
(12 answers)
Custom fonts and XML layouts (Android)
(18 answers)
Closed 9 years ago.
How can I use a custom font which was added in the asset folder in my xml? I know we can use setTypeface() method in java, but we have to do this everywhere where we use that TextView. So is there a better way?

The best way i found by googling is- Say if you want to use in TextView then we have to extend the Textview and have to set the font in that later we can use our customised Textview in our xml. I'll show the extended TextView below
package com.vins.test;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"your_font.ttf");
setTypeface(tf);
}
}
We calling init() to set font in each of the costructors.
Later we have to use this in our main.xml as shown below.
<com.vins.test.MyTextView
android:id="#+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1"
android:text="This is a text view with the font u had set in MyTextView class "
android:textSize="30dip"
android:textColor="#ff0000"
>
Update:
Be aware about the memory leak in pre-4.0 Android as mentioned by pandre.

Put your font file in asset\fonts\fontname
Define three textview in your xml file then, put this code in your activity class:
public class AndroidExternalFontsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Font path
String fontPath = "fonts/DS-DIGIT.TTF";
String fontPath1 = "fonts/Face Your Fears.ttf";
String fontPath2 = "fonts/HelveticaNeue-Bold_0.otf";
// text view label
TextView txtGhost = (TextView) findViewById(R.id.ghost);
TextView txtGhost1 = (TextView) findViewById(R.id.ghost1);
TextView txtGhost2 = (TextView) findViewById(R.id.ghost2);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
Typeface tf1 = Typeface.createFromAsset(getAssets(), fontPath1);
Typeface tf2 = Typeface.createFromAsset(getAssets(), fontPath2);
// Applying font
txtGhost.setTypeface(tf);
txtGhost1.setTypeface(tf1);
txtGhost2.setTypeface(tf2);
}
}

Related

How to apply an external font for a complete Android app?

I want to change the font of my complete app!
But I don't know how to access the complete application.
I have a way to access a text by Id, how can I change the code to access the whole App?
public class ExternalFont extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String fontPath = "fonts/FreeUniversal-Regular.ttf";
TextView txtUniversal = (TextView) findViewById(R.id.universal);
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
txtUniversal.setTypeface(tf);
}
}
To change all typeface for all TextView in app you should create custom style then add it into AppTheme style.
`<style name="customTextVeiw" parent="Widget.MaterialComponents.TextView">
<item name"fontFamilt">#font/custom_free_universal_regular</item>`
then add this style inside style.xml file inside AppTheme style.
`<style name="AppTheme" parent="AppBaseTheme">
<item name="android:textViewStyle">#style/customTextVeiw</item>`
Unfortunately there is no direct way in which you can change the typeface of all the TextViews you are using in your app by just changing the default typeface.
What you can do is create your own custom TextView and set typeface on it as suggested by #josedlujan. But the flaw in that approach is that each time a TextView object will be created, a new Typeface object will be created which is extremely bad for RAM usage (A Typeface object typically varies from 8-13 kb for typefaces like Roboto). So it is better to cache your Typeface once it has got loaded.
Step 1: Create a Typeface cache for your app -
public enum Font {
// path to your font asset
Y("fonts/Roboto-Regular.ttf");
public final String name;
private Typeface typeface;
Font(String s) {
name = s;
}
public Typeface getTypeface(Context context) {
if (typeface != null) return typeface;
try {
return typeface = Typeface.createFromAsset(context.getAssets(), name);
} catch (Exception e) {
return null;
}
}
public static Font fromName(String fontName) {
return Font.valueOf(fontName.toUpperCase());
}
Step 2: Define your own custom attribute "customFont" in attrs.xml for your CustomTextView
attrs.xml -
<declare-styleable name="CustomFontTextView">
<attr name="customFont"/>
</declare-styleable>
<com.packagename.CustomFontTextView
android:id="#+id/some_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:customFont="rl"/>
Step 3: Create your own custom TextView
public class CustomFontTextView extends TextView {
public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public CustomFontTextView(Context context) {
super(context);
init(context, null);
}
private void init(Context context, AttributeSet attrs) {
if (attrs == null) {
return;
}
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFontTextView, 0 ,0);
String fontName = a.getString(R.styleable.CustomFontTextView_customFont);
String textStyle = attrs.getAttributeValue(styleScheme, styleAttribute);
if (fontName != null) {
Typeface typeface = Font.fromName(fontName).getTypeface(context);
if (textStyle != null) {
int style = Integer.decode(textStyle);
setTypeface(typeface, style);
} else {
setTypeface(typeface);
}
}
a.recycle();
}
To use Font for all app text you should use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher.
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 like this free_universal_regular.ttf
you should start your font with lower and under score instead of -.
Creating 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 e.g: custom_free_universal_regular.xml , and then click OK. The new font resource XML opens in the editor.
add this in custom_free_universal_regular.xml file.
<?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/free_universal_regular" /> </font-family>
Now we can use this font family anywhere in our app like this
For e.g for all app use it inside the style.xml
<style name="BaseTheme" parent=""> <item name="fontFamily">#font/custom_free_universal_regular</item>
or in a specific element use it like this
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="#font/custom_free_universal_regular"/>
I hope that could help.
Create your own Textview with custom style.
Example:
public class YourTextView extends TextView {
public YourTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public YourTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public YourTextView(Context context) {
super(context);
init();
}
private void init() {
Typeface tf = Typeface.createFromAsset(context.getAssets(),
"fonts/yourfont.ttf");
setTypeface(tf);
}
}
You can use in yours XML.

Different fonts with different locale?

How to set different fonts with different locale?
lets assume i am having a string file hi hindi but my phone don't support hindi fonts, how to add fonts from asset as default font though out the application?
To add custom font,Please follow below Steps.
Create a folder named fonts in assets folder.
put your custom font in fonts folder.(You can also put your custom fonts in assets folder).
3.Add below code in your java file
Typeface tfFonts = Typeface.createFromAsset(getAssets(),"fonts/customfont.ttf");
componentName.setTypeface(tfFonts);
First, copy your customized font file (eg custom.ttf) in assets folder.
Then, do like this
1) Add this class OpenHindiFonts.java
import android.content.Context;
import android.graphics.Typeface;
public class OpenHindiFonts {
private static OpenHindiFonts instance;
private static Typeface typeface;
public static OpenHindiFonts getInstance(Context context) {
synchronized (OpenHindiFonts.class) {
if (instance == null) {
instance = new OpenHindiFonts();
typeface = Typeface.createFromAsset(context.getResources().getAssets(), "custom.ttf");
}
return instance;
}
}
public Typeface getTypeFace() {
return typeface;
}
}
2) Add this class - NativelyCustomTextView.
package com.packageName;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class NativelyCustomTextView extends TextView {
public NativelyCustomTextView(Context context) {
super(context);
setTypeface(OpenHindiFonts.getInstance(context).getTypeFace());
}
public NativelyCustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTypeface(OpenHindiFonts.getInstance(context).getTypeFace());
}
public NativelyCustomTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setTypeface(OpenHindiFonts.getInstance(context).getTypeFace());
}
}
3) In your layout xml, need to use this -
<com.packageName.NativelyCustomTextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hindi_text"
android:textColor="#727272"
android:textSize="18dp" />
4) And in your activity code, no need to change anything -
final TextView textV = (TextView) findViewById(...);
textV.setText(getResources().getString(R.string.hindi_text));
#Test limbs:this is what i suggest to you:create all the needed font in the activity by this way :
Typeface tfFonts =Typeface.createFromAsset(getAssets(),"fonts/customfont.ttf");
componentName.setTypeface(tfFonts);
hindi,bangli,what ever you want.create a current Typefacevariable and provide a way to set it dynamically.all what you need than is is to assign all your widget with the font typeface you want.
lefttext.setTypeface((MainActivity.getCurrentTypeface()));
lefttext is the widget you need to set its font.
getCurrentTypeface is a method you create in the main activity to get a reference to the current font.this way you can assign all widget that you need

Use external font for many texts [duplicate]

This question already has answers here:
Using custom font in android TextView using xml
(11 answers)
Closed 9 years ago.
hi there i am newer in android and i want to ask how to use one font for many text views i have use this method
final String DosisPath = "fonts/Dosis-Bold.ttf";
final Typeface Dosis_Bold = Typeface.createFromAsset(getAssets(), DosisPath);
TextView txtCancle = (TextView) findViewById(R.id.cancle);
txtCancle.setTypeface(Dosis_Bold);
and it's work good but i try to make the same Typeface for another TextView but that dosen't work like this
final String DosisPath = "fonts/Dosis-Bold.ttf";
final Typeface Dosis_Bold = Typeface.createFromAsset(getAssets(), DosisPath);
TextView txtCancle = (TextView) findViewById(R.id.cancle);
txtCancle.setTypeface(Dosis_Bold);
EditText ETCode = (EditText)findViewById(R.id.secET);
ETCode.setTypeface(Dosis_Bold);
if the is an error i have done tell me and if there is another way to make that tell me too thanks alot .
This is how you should do it.
Create a class
public class TextViewContent extends TextView {
public TextViewContent(Context context) {
super(context);
setCustomFont(context);
}
public TextViewContent(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context);
}
public TextViewContent(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (isInEditMode()) {
return;
}
setCustomFont(context);
}
private void setCustomFont(Context ctx) {
setTypeface(Typeface.createFromAsset(ctx.getAssets(),
"Champagne_Limousines.ttf"));
}
}
and in your layout file
<com.hardik.test.widget.TextViewContent
style="#style/TextMedium"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginTop="5dip"
android:gravity="center"
android:text="#string/tag_line" />
This will display textview in chosen font. Same way for EditText you can extends the EditText class and rest is same.

Setting Button text font in android

I have a button created using android widgets. I want to set the font of the button text to Helv Neue 67 Med Cond. How to get this font and set it to the button text in android layout file?
I guess you may have already found the answer, but if not (and for other developers), you can do it like this:
1.you want to save the "Helv Neue 67 Med Cond.ttf" in to assets folder.
then
For TextView
TextView txt = (TextView) findViewById(R.id.custom_font);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Helv Neue 67 Med Cond.ttf");
txt.setTypeface(typeface);
For Button
Button n=(Button) findViewById(R.id.button1);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Helv Neue 67 Med Cond.ttf");
n.setText("show");
n.setTypeface(typeface);
First you have to put the ttf file in assets folder and then You can use the below code to set Custom font in TextView, same way you can do for Button:
TextView txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "Helv Neue 67 Med Cond.ttf");
txt.setTypeface(font);
If you plan to add the same font to several buttons I suggest that you go all the way and implement subclass button:
public class ButtonPlus extends Button {
public ButtonPlus(Context context) {
super(context);
applyCustomFont(context);
}
public ButtonPlus(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context);
}
public ButtonPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context);
}
private void applyCustomFont(Context context) {
Typeface customFont = FontCache.getTypeface("fonts/candy.ttf", context);
setTypeface(customFont);
}
}
And here's the FontCache to reduce memory usage on older devices:
public class FontCache {
private static Hashtable<String, Typeface> fontCache = new Hashtable<>();
public static Typeface getTypeface(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;
}
}
And finally an example use in a layout:
<com.my.package.buttons.ButtonPlus
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_sometext"/>
This may seem like an awful lot of work, but you'll thank me once you have couple of handfuls of buttons and textfields that you want to change font on.
Also you can see this tutorial and a example in GitHub.
Android comes with 3 fonts (Sans, Serif, Monospace) which can be accesed using android:typeface=”FONT_NAME”.
For using custom font, you should use code like
TextView txt = (TextView) findViewById(R.id.custom_font);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Helv Neue 67 Med Cond.ttf");
txt.setTypeface(typeface);
Some similar questions are Custom Fonts in Android and Android - Using Custom Font.
You can use:
android:typeface="yourfont"
You have to download Helv Neue 67 Med Cond font and store it in assets folder. let the downloaded font is myfont.ttf
Use the following code to set the font
Typeface tf = Typeface.createFromAsset(getAssets(), "myfont.ttf");
TextView TextViewWelcome = (TextView)findViewById(R.id.textViewWelcome);
TextViewWelcome.setTypeface(tf);
Thanks
Deepak
This is a good article, I used it several times and works:
http://mobile.tutsplus.com/tutorials/android/customize-android-fonts/

Custom Fonts in Android

I have already read some articles and searched on Google, but I failed to do it.
My problem is regarding the font-face.
In Android, there are only 4 attributes in "android:typeface": Normal, Sans, Serif, Monospace.
So what do I have to do to use "Verdana" in my application?
Please suggest me a correct way to use this font in my Android application.
This is a simple example... create a folder in the root of your project called assets/fonts/ then paste the TTF font file (in this case Verdana.ttf). Then, if you want to apply that font to, say a TextView, do the following:
import android.graphics.Typeface;
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/Verdana.ttf");
tv.setTypeface(face);
}
}
This example was taken from the ComonsWare book (written by Mark Murphy). You can download the full example from GitHub.
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" />
Well!!
This question is pretty old but still if someone is looking for the answer(in 2015) on how to apply custom font to all the Textviews through xml code directly see below:
First:
we need to add custom font inside assets folder inside your app directory:
.ttf or .otf both work in case of Android
Second:
Create Class CustomTextView which extends TextView like below:
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setTypeface(Typeface tf) {
super.setTypeface(FontCache.getFont(getContext(),"fonts/<font_name>"));
}
}
Third:
FontCache class being used inside CustomTextView's setTypeface() method.Purpose is to do basic Font Caching using HashMap:
public class FontCache {
private static Map<String,Typeface> fontMap = new HashMap<String,Typeface>();
public static Typeface getFont(Context context,String fontname){
if(fontMap.containsKey(fontname)){
return fontMap.get(fontname);
}
else{
Typeface tf = Typeface.createFromAsset(context.getAssets(),fontname);
fontMap.put(fontname,tf);
return tf;
}
}
}
Fourth:[Final step]
All we do now is use the CustomTextView directly inside our xml file wherever custom font textview is required:
<<package_name>.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Font Text"
android:textSize ="18sp"
android:textAppearance="?android:textAppearanceSmall"
android:id="#+id/custom_txt"
/>
Sorry, if this has already been posted somewhere on SO. Just thought to share if it helps someone!!
You can use 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.
This library does not provides Verdana Font face.
But provide following font faces. Which might you would like to use.
Roboto
Droid Serif
Droid Robot
Freedom
Fun Raiser
Android Nation
Green Avocado
Recognition
Simply:
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(EasyFonts.robotoThin(this));
I am author of this library.
To change the (custom) font of your app globally, have a look at Calligraphy
Simply add Calligraphy to your gradle.build and add the following snippet to your Application.onCreate():
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/MyCustomFont.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
and in every Activity add the following:
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
That is all you need to do to change the font globally in your App. Have a look at the docs for more details.
// My example show you how to change fonts into a normal textView or list view
create a fonts folder into your assets dir of android and copy your custom font in that ..
assets/fonts/monaco.ttf
// Font path
String fontPath = "fonts/monaco.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// CASE 1 : Inside your list view
holder.name = (TextView) convertView
.findViewById(R.id.textView_cityName);
// set name of text in each row
holder.name.setText(CitiesNames.get(position));
// set the type of font you want to set
holder.name.setTypeface(tf);
// CASE 2 : Inside your text view
TextView tx = (TextView)findViewById(R.id.textview1);
tx.setTypeface(tf);
//vKj
TextView textView = (Textview) findViewById(R.id.mytext);
Typeface face=Typeface.createFromAsset(getAssets(),
"fonts/Verdana.ttf");
textView.setTypeFace(face);

Categories

Resources