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);
Related
I'm new in android working on an app that gives the user info about all font's of Google.
For that, I need to make an app with a TextView Something like this
On click of the TextView, the font will change With text.
I'm thinking about using onclicklistener
you can put "your_font.ttf" file in asset folder then import it with
Typeface custom_font_1 = Typeface.createFromAsset(getAssets(), "your_font.ttf");
then assign it to your showCaseTextView with this
showCaseTextView.setTypeFace(custom_font_1);
then in your onClickListener of showCaseTextView to change your specifiedTextView font do like this
specifiedTextView.setTypeFace(custom_font_1);
and repeat it for other fonts.
You can implement your own custom font with TextView, EditText, Button etc.. by using android attributes.
How to
-Here are some steps to use:
1.Create attribute file (res->values->attrs.xml)
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<declare-styleable name="TextElement">
<attr name="font" format="string"/>
<attr name="underline" format="boolean"/>
</declare-styleable>
</resources>
2.Create Custom TextView class (anywhere in java folder)
3. Use attributes inside your layout file
4. and just run your code.
Here is the full example of your question, you can go through this exmaple:
Full Demonstration
Have 2 way to archive this
1st way
public class FontCache {
private static HashMap<String, Typeface> fontCache = new HashMap<>();
public static Typeface getTypeface(String fontname, Context context) {
Typeface typeface = fontCache.get(fontname);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.getAssets(), fontname);
} catch (Exception e) {
return null;
}
fontCache.put(fontname, typeface);
}
return typeface;
}
}
This caches the fonts while minimizing the number of accesses to the assets. Now, since we've a method to access our custom font, let's implement a class, which extends TextView.
Extending TextView
Next, we'll create a new Java class, which extends TextView. This allows us to use that class in all XML views. It inherits all functionality and properties of a regular TextView; but adds our custom font.
Once again, we're taking a peek at the source code of our eat foody project. The code might look complex for a second, but is straight-forward:
public class EatFoodyTextView extends TextView {
public EatFoodyTextView(Context context) {
super(context);
applyCustomFont(context);
}
public EatFoodyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context);
}
public EatFoodyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context);
}
private void applyCustomFont(Context context) {
Typeface customFont = FontCache.getTypeface("SourceSansPro-Regular.ttf", context);
setTypeface(customFont);
}
}
The first three methods are just constructors, which we override to call a single method applyCustomFont(). That method is the important piece of the puzzle. It simply gets the (hopefully cached) font from our FontCache class. Lastly, we've to call setTypeface() with the font and we're almost done. In case you're wondering, we can call the setTypeface() directly (and not on a TextView object), since we're extending the TextView class.
Using the Class
You might wonder, if so much preparation is worth the effort. In this section you'll see that it is indeed. Because all you've left to do is use the class in an XML view and it automatically has your custom font. There is no Java code necessary!
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.futurestudio.foody.views.EatFoodyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:layout_marginBottom="24dp"/>
</RelativeLayout>
As you can see, you can continue to use all niceties (e.g. textSize, textColor) of TextView. Now, just replace all elements with the class we just created, for example and you applied your custom font everywhere!
(Ref: https://futurestud.io/tutorials/custom-fonts-on-android-extending-textview)
2nd way
Follow Google guide support from API 26 (Android 8) https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml
Make change between textview to change font
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textview_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:layout_marginBottom="24dp"/>
<com.futurestudio.foody.views.EatFoodyTextView
android:id="#+id/textview_custom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:visibility="gone"
android:layout_marginBottom="24dp"/>
</RelativeLayout>
attention at android:visibility="gone"
in Activity you use this code to toggle between 2 TextViews
final TextView normalTextView = findViewById(R.id.textview_normal);
final TextView customTextView = findViewById(R.id.textview_custom);
normalTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
normalTextView.setVisibility(View.GONE);
customTextView.setVisibility(View.VISIBLE);
}
});
customTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
normalTextView.setVisibility(View.VISIBLE);
customTextView.setVisibility(View.GONE);
}
});
This question already has answers here:
How to set default font family for entire Android app
(16 answers)
Closed 9 years ago.
I have one application in Which I want to change font of text in whole application.
Is there anyway to change font of application Programmatically or with xml in manifest.?
Try this
1.place your ttf file in assets folder and add these lines to your java file
Typeface font = Typeface.createFromAsset(activity.getAssets(),"fonts/androidnation.ttf");
tv.setTypeface(font);
2.To set it through xml
XML Typeface
Place you fonts in fonts folder and then use the following code.
TextView tv = (TextView) findViewById(R.id.appname);
Typeface face = Typeface.createFromAsset(getAssets(),"fonts/epimodem.ttf");
tv.setTypeface(face);
This is the way to set font programmatically.
Create fonts folder in asset and paste the fonts whatever you want to paste.
Create one class. Name it Typesafe.java
public enum TypeSafe {
HELVETICANEUELTCOMBD,
HELVETICANEUELTCOMBDCN,
HELVETICANEUELTCOMCN,
}
After that create one method in your Activity or if you have the Utility class.
public void setTypeface(TextView textView, TypeSafe type, AssetManager assetManager){
if (TypeSafe.HELVETICANEUELTCOMBD.equals(type)) {
final Typeface typeface = Typeface.createFromAsset(assetManager, "fonts/HelveticaNeueLTCom-Bd.ttf");
textView.setTypeface(typeface);
} else if (TypeSafe.HELVETICANEUELTCOMBDCN.equals(type)) {
final Typeface typeface1 = Typeface.createFromAsset(assetManager, "fonts/HelveticaNeueLTCom-BdCn.ttf");
textView.setTypeface(typeface1);
}
}
Call these method in your activity.
setTypeface(yourtextView, TypeSafe.HELVETICANEUELTCOMLT, getAssets());
The easiest way to do it is creating your own TextView:
public class MyTextView extends TextView {
public DMTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// you need your TypefaceFile "myTypeface.ttf" in the assets folder of your project
setTypeface(Typeface.createFromAsset(context.getAssets(),"myTypeface.ttf"));
}
// add the other constructors if you want
}
now, you can use it anywhere in your xml:
<com.your.package.MyTextView ... > just like normal textviews
It might be improved by caching the Typeface, so you don't have to create it again with every Reference to your TextView.
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;
}
}
I'm trying to use Font Awesome on my application, I was able to integrate the font using Typeface.createFromAsset(), but I also want to use the icons provided by this font, but so far I haven't been able to do that.
This particular font contains icons inside the Unicode Private Use Area (PUA), for things like media player controls, file system access, arrows, etc.
Has anybody used fonts that contain icons and symbols on Android, is this possible at all?
Font Awesome seems to be working fine for me in my android app. I did the following:
Copied fontawesome-webfont.ttf into my assests folder
Found the character entities for icons I wanted, using this page: http://fortawesome.github.io/Font-Awesome/cheatsheet/
Created an entry in strings.xml for each icon. Eg for a heart:
<string name="icon_heart"></string>
Referenced said entry in the view of my xml layout:
<Button
android:id="#+id/like"
style="?android:attr/buttonStyleSmall"
...
android:text="#string/icon_heart" />
Loaded the font in my onCreate method and set it for the appropriate Views:
Typeface font = Typeface.createFromAsset( getAssets(), "fontawesome-webfont.ttf" );
...
Button button = (Button)findViewById( R.id.like );
button.setTypeface(font);
Try IcoMoon: http://icomoon.io
Pick the icons you want
Assign characters to each icon
Download the font
Say, you picked the play icon, assigned the letter 'P' to it, and downloaded the file icomoon.ttf to your asset folder. This is how you show the icon:
xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="48sp"
android:text="P" />
java:
Typeface typeface = Typeface.createFromAsset(getAssets(), "icomoon.ttf");
textView.setTypeface(typeface);
I've given a talk on making beautiful Android apps, which includes explanation on using icon fonts, plus adding gradients to make the icons even prettier:
http://www.sqisland.com/talks/beautiful-android
The icon font explanation starts at slide 34:
http://www.sqisland.com/talks/beautiful-android/#34
Maybe too late but I had the same need so I've published this https://github.com/liltof/font-awsome-for-android
It's an android ready xml version of font awesome usable just like Keith Corwin said
Hope it will help others.
As above is great example and works great:
Typeface font = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf" );
Button button = (Button)findViewById( R.id.like );
button.setTypeface(font);
BUT! > this will work if string inside button you set from xml:
<string name="icon_heart"></string>
button.setText(getString(R.string.icon_heart));
If you need to add it dynamically can use this:
String iconHeart = "";
String valHexStr = iconHeart.replace("&#x", "").replace(";", "");
long valLong = Long.parseLong(valHexStr,16);
button.setText((char) valLong + "");
If you want programmatic setText without add string to string.xml
see its hexadecimal code here:
http://fortawesome.github.io/Font-Awesome/cheatsheet/
replace to 0xf066
Typeface typeface = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf");
textView.setTypeface(typeface);
textView.setText(new String(new char[]{0xf006 }));
There is small and useful library designed for this purposes:
dependencies {
compile 'com.shamanland:fonticon:0.1.9'
}
Get demo on Google Play.
You can easily add font-based icon in your layout:
<com.shamanland.fonticon.FontIconView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ic_android"
android:textSize="#dimen/icon_size"
android:textColor="#color/icon_color"
/>
You can inflate font-icon as Drawable from xml:
<?xml version="1.0" encoding="utf-8"?>
<font-icon
xmlns:android="http://schemas.android.com/apk/res-auto"
android:text="#string/ic_android"
android:textSize="#dimen/big_icon_size"
android:textColor="#color/green_170"
/>
Java code:
Drawable icon = FontIconDrawable.inflate(getResources(), R.xml.ic_android);
Links:
Project page
Github repo
I made this helper class in C# (Xamarin) to programmatically set the text property. It which works pretty well for me:
internal static class FontAwesomeManager
{
private static readonly Typeface AwesomeFont = Typeface.CreateFromAsset(App.Application.Context.Assets, "FontAwesome.ttf");
private static readonly Dictionary<FontAwesomeIcon, string> IconMap = new Dictionary<FontAwesomeIcon, string>
{
{FontAwesomeIcon.Bars, "\uf0c9"},
{FontAwesomeIcon.Calendar, "\uf073"},
{FontAwesomeIcon.Child, "\uf1ae"},
{FontAwesomeIcon.Cog, "\uf013"},
{FontAwesomeIcon.Eye, "\uf06e"},
{FontAwesomeIcon.Filter, "\uf0b0"},
{FontAwesomeIcon.Link, "\uf0c1"},
{FontAwesomeIcon.ListOrderedList, "\uf0cb"},
{FontAwesomeIcon.PencilSquareOutline, "\uf044"},
{FontAwesomeIcon.Picture, "\uf03e"},
{FontAwesomeIcon.PlayCircleOutline, "\uf01d"},
{FontAwesomeIcon.SignOut, "\uf08b"},
{FontAwesomeIcon.Sliders, "\uf1de"}
};
public static void Awesomify(this TextView view, FontAwesomeIcon icon)
{
var iconString = IconMap[icon];
view.Text = iconString;
view.SetTypeface(AwesomeFont, TypefaceStyle.Normal);
}
}
enum FontAwesomeIcon
{
Bars,
Calendar,
Child,
Cog,
Eye,
Filter,
Link,
ListOrderedList,
PencilSquareOutline,
Picture,
PlayCircleOutline,
SignOut,
Sliders
}
Should be easy enough to convert to Java, I think. Hope it helps someone!
One of the libraries that I use for Font Awesome is this:
https://github.com/Bearded-Hen/Android-Bootstrap
Specifically,
https://github.com/Bearded-Hen/Android-Bootstrap/wiki/Font-Awesome-Text
The documentation is easy to understand.
First, add the needed dependencies in the build.gradle:
dependencies {
compile 'com.beardedhen:androidbootstrap:1.2.3'
}
Secondly, you can add this in your XML:
<com.beardedhen.androidbootstrap.FontAwesomeText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fontawesometext:fa_icon="fa-github"
android:layout_margin="10dp"
android:textSize="32sp"
/>
but make sure you add this in your root layout if you want to use above code example:
xmlns:fontawesometext="http://schemas.android.com/apk/res-auto"
The FontView library lets you use normal/unicode font characters as icons/graphics in your app. It can load the font via assets or a network location.
The benefit of this library is that:
1 - it takes care of remote resources for you
2 - scales the font size in dynamically sized views
3 - allows the font to easily be styled.
https://github.com/shellum/fontView
Example:
Layout:
<com.finalhack.fontview.FontView
android:id="#+id/someActionIcon"
android:layout_width="80dp"
android:layout_height="80dp" />
Java:
fontView.setupFont("fonts/font.ttf", character, FontView.ImageType.CIRCLE);
fontView.addForegroundColor(Color.RED);
fontView.addBackgroundColor(Color.WHITE);
There's another nice solution which you can use in your layout xml files directly and does not require to use setTypeface.
It is Joan Zapata's Iconify. You can read here what's new in Iconify v2. It includes 9 different font libraries which you can simply use by adding dependencies to your build.gradle file.
In the layout xml files it's possible to choose between these widgets:
com.joanzapata.iconify.widget.IconTextview
com.joanzapata.iconify.widget.IconButton
com.joanzapata.iconify.widget.IconToggleButton
Initially create asset folder and copy the fontawesome icon (.ttf)
How to create asset folder?
app-->right Click -->new-->folder --> asset folder
next step download how to download .ttf file?
click here--> and click download button after download extract and open web fonts. finally choose true text style(ttf)paste asset folder.
how to design xml and java file in android ?
app-->res-->values
string.xml
resources
string name="calander_font" > <string
resources
this example of one font more Unicode click here
Activity_main.xml
<TextView
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/calander_view"/>
MainActivity.java
calander_tv = (TextView)findViewById(R.id.calander_view);
Typeface typeface = Typeface.createFromAsset(getAssets(),"/fonts/fa-solid-900.ttf");
calander_tv.setTypeface(typeface);
calander_tv.setText(R.string.calander_font);
Output:
Output image
I'm a bit late to the party but I wrote a custom view that let's you do this, by default it's set to entypo, but you can modify it to use any iconfont: check it out here: github.com/MarsVard/IconView
//
edit the library is old and not supported anymore...
new one here https://github.com/MarsVard/IonIconView
In case you only need a few font awesome icons, you can also use http://fa2png.io to generate normal pixel images. But if you add new icons/buttons regularly I'd recommend the .ttf version as its more flexible.
If someone wonders how to add it programmitcally you gotta do it this way.
button_info.setText(R.string.icon_heart);
button_info.append(" Hallo"); //<<--- This is the tricky part
As all answers are great but I didn't want to use a library and each solution with just one line java code made my Activities and Fragments very messy.
So I over wrote the TextView class as follows:
public class FontAwesomeTextView extends TextView {
private static final String TAG = "TextViewFontAwesome";
public FontAwesomeTextView(Context context) {
super(context);
init();
}
public FontAwesomeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fontawesome-webfont.ttf");
setTypeface(tf);
}
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface typeface = null;
try {
typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
what you should do is copy the font ttf file into assets folder .And use this cheat sheet for finding each icons string.
hope this helps.
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.