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/
Related
I am trying to build a simple app for localisation of a locale language
"Meitei mayek" of Manipur, India
which is not in the Android locale list.
I have the .ttf file.
How do i do it?
Create fonts directory under assets and put .ttf file in fonts.
assets/fonts
Use below code whenever you want to set.
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(myTypeface);
You can create a custom TextView to support the custom font for displaying text. Try :
1- Place the .ttf font file in the assets folder of your project.
2- Create a class to extend TextView
public class TextViewIndian extends AppCompatTextView {
public TextViewIndian(Context context) {
super(context);
setTypeface(FontFactory.getInstance(context).getMyFont());
}
public TextViewIndian(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTypeface(FontFactory.getInstance(context).getMyFont());
}
public TextViewIndian(Context context, AttributeSet attrs) {
super(context, attrs);
setTypeface(FontFactory.getInstance(context).getMyFont());
}
}
As seen above you need to creare another class called FontFactory to load the font files from assets, in a singleton way to avoid memory leaks.
public class FontFactory {
private static Typeface MYFONT;
private static FontFactory instance ;
private FontFactory(Context context){
MYFONT = Typeface.createFromAsset(context.getAssets(),"font.ttf");
}
public static FontFactory getInstance(Context context){
if(instance == null)
instance = new FontFactory(context);
return instance ;
}
public Typeface getMyFont(){
return MYFONT;
}
}
You can use this same approach for other widgets like Button and EditText to create custom ones for your language.
Now you can place this TextViewIndian in your layout.xml files and use them the way you use any other widget and it automatically sets the custom font for its text.
I've found several posts regarding this topic, but all of this topics either sets the font with setTypeFace() method on a TextView object, or creating a custom class which sets the font to Roboto and extends TextView. As far as I know from API-Level 11(?) or something, we are able to set the TypeFace as a xml attribute, some how. Like this:
<TextView
android:id="#+id/profileHeader"
android:layout_width="100dp"
android:layout_height="100dp"
android:typeface="roboto"
android:text="Hello, world">
</TextView>
What is the right way to do this? Is it possible to have a fallback if the application runs on a device lower than API level 11(?) something like:
android:typeface="roboto|monospace|serif"
Take a look at the RobotoTextView project. Works down to Android 1.5, and you can set the typeface using XML attributes. It also includes other views like RobotoButton, RobotoCheckbox, etc.
I don't see a way you can define an external typeface as a xml attribute. You should store the typeface in the assets and call:
tv.setTypeface( Typeface.createFromAsset( context.getAssets(), roboto.ttf ) );
You can not set font directly from assets like this you have to do as follow in onCreate. This will make same thing what you want to do.
TextView tvTextView = (TextView) findViewById(R.id.textView1);
Typeface typeface = Typeface.createFromAsset(getAssets(),"Roboto.ttf");
tvTextView.setTypeface(typeface);
Hope it will help you out.:D
The android:typeface attribute only has a few valid options (according to the Android docs)...
normal
sans
serif
monospace
If you need the Roboto font in your app for older devices, you need to include the Roboto TTF files into your project.
The most obvious way to use these fonts is to use the setTypeface() method of TextView, but if you want to specify it in XML instead, you must create a custom TextView and create your own styleable attribute for your custom TextView.
This topic is all over the Internet.
For JellyBean (4.1) onward you can use the method provided in this StackOverflow topic. It will fallback gracefully to sans in older devices.
If you must fallback to monospace or serif, declare a folder layout-v16 where you use the font you chose, i.e., "sans-serif-condensed", and in the default folder you use the "monospace" or "serif" font.
If you want to fallback to a non-default font, you can programatically check the android version and choose the appropriate action, i.e.:
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
TextView textView = (TextView) findViewById(R.id.textView_id);
Typeface myFont = Typeface.createFromAsset(getAssets(),"RobotoCondensed.ttf");
textView.setTypeface(myFont);
}
This is for future people running in to the same issue as I have. Setting typeface tends to take up lot of memory when it comes to loading multiple rows. Using the following two codes together to actually make it work smoothly. I got the solution from stackoverflow but they answers were not listed together.
public class RobotoTextView extends TextView {
Context context;
public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
public RobotoTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public RobotoTextView(Context context) {
super(context);
this.context = context;
}
public void setTypeface(Typeface tf, int style) {
if (!isInEditMode()) {
if (style == Typeface.NORMAL) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-Light.ttf"));
} else if (style == Typeface.ITALIC) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-LightItalic.ttf"));
} else if (style == Typeface.BOLD) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-Bold.ttf"));
} else if (style == Typeface.BOLD_ITALIC) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-BoldItalic.ttf"));
}
}
}
public class TypeFaceProvider {
private static Hashtable<String, Typeface> sTypeFaces = new Hashtable<String, Typeface>(
4);
public static Typeface getTypeFace(Context context, String fileName) {
Typeface tempTypeface = sTypeFaces.get(fileName);
if (tempTypeface == null) {
tempTypeface = Typeface.createFromAsset(context.getAssets(),
fileName);
sTypeFaces.put(fileName, tempTypeface);
}
return tempTypeface;
}
}
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);
}
}
I was looking for some stylish fonts for my android application. but the problem is how can i make my android application supportable for external fonts.
Thank you.
You need to create fonts folder under assets folder in your project and put your TTF into it. Then in your Activity onCreate()
TextView myTextView=(TextView)findViewById(R.id.textBox);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/mytruetypefont.ttf");
myTextView.setTypeface(typeFace);
Please note that not all TTF will work. While I was experimenting, it worked just for a subset (on Windows the ones whose name is written in small caps).
You can use the custom TextView for whole app with custom font here is an example for that
public class MyTextView extends TextView {
Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_REGULAR);
Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_BOLD);
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(boldTypeface/*, -1*/);
} else {
super.setTypeface(normalTypeface/*, -1*/);
}
}
}
Create a folder named fonts in the assets folder and add the snippet from the below link.
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);
To implement you need use Typeface go through with sample below
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
if (view instanceof TextView)
{
TextView textView = (TextView) view;
textView.setTypeface(typeface);
}
}
}
The easiest way to accomplish this is to package the desired font(s)
with your 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.
Then, you need to tell your widgets to use that font. Unfortunately,
you can no longer use layout XML for this, since the XML does not know
about any fonts you may have tucked away as an application asset.
Instead, you need to make the change in Java code, by calling
Typeface.createFromAsset(getAssets(), “fonts/HandmadeTypewriter.ttf”),
then taking the created Typeface object and passing it to your
TextView via setTypeface().
For more reference here is the tutorial where I got this:
http://www.androidguys.com/2008/08/18/fun-with-fonts/
I recommend this approach it very nice with adding name of custom font in typeface to styles.xml and putting your set of fonts into assets folder.
One more point in addition to the above answers.
When using a font inside a fragment, the typeface instantiation should be done in the onAttach method ( override ) as given below:
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
}
Reason:
There is a short span of time before a fragment is attached to an activity. If CreateFromAsset method is called before attaching fragment to an activity an error occurs.
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);