ChatGPT解决这个技术问题 Extra ChatGPT

How to use icons and symbols from "Font Awesome" on Native Android Application

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?

I've updated the link
I don't agree that this is off-topic for Stack Overflow. It seems to me that it fits these (stackoverflow.com/help/on-topic) guidelines, as it's: about a specific programming problem (how to apply a specific font-based icon set to a specific mobile platform), and it's a practical, answerable problem (see my answer below, which I think illustrates that).
Check out this repo for implementing font awesome in android github.com/bperin/FontAwesomeAndroid
check this library: blog.shamanland.com/p/android-fonticon-library.html, it's available on Maven Central. see demo-app: play.google.com/store/apps/…

h
hsz

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: Referenced said entry in the view of my xml layout:

c
chiuki

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


l
liltof

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.


Welcome to SO. I saw your code is not too long. Why don't you post it at this answer? Links can crash with time.
I have been using this great .xml file for weeks. But now I've realized that it misses fa_times. Can you please update it ? Edit: oh, it is fa_remove. or icon_remove in your file.
How to add text as well as icon in button using awesome font? Like add drawable left or drawable right in button.
u
user1540907

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">&#xf004;</string>
button.setText(getString(R.string.icon_heart));

If you need to add it dynamically can use this:

String iconHeart = "&#xf004;";
String valHexStr = iconHeart.replace("&#x", "").replace(";", "");
long valLong = Long.parseLong(valHexStr,16);
button.setText((char) valLong + "");

best way ever! thanks i give + vote _ just attention button is textview and replace String.valueOf with get string
Finally a solution to use font awesome. Thanks a lot!
H
Haryanto

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 }));

O
Oleksii K.

There is small and useful library designed for this purposes:

dependencies {
    compile 'com.shamanland:fonticon:0.1.9'
}

Get demo on Google Play.

https://i.stack.imgur.com/XpDxr.png

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


really good library, thank you. the inflatable xml-definitions are a little pain though, I prefer to directly use the FontIconView
I tested this in a Lenovo with Android 4.2.2 and the icons dont showed up, what can be?
Try the latest version 0.1.9
A
Andres Sepulveda

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!


A
Abdul Rahman A Samad

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"

I followed this but I got the error: Error:(54) No resource identifier found for attribute 'fa_icon' in package 'xxx.yyy'
@Hajjat to use this you need to use version 1.2.3. I just updated the code to reflect that. Try it.
D
David Passmore

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);

Does it cache the Typeface object in memory? There's a known potential for a memory leak when handling fonts on Android.
g
gus27

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

R
Rishabh Agarwal

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" >&#xf073; <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


M
Mars

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


Your library is not caching the Typeface and, instead, is constructing it every time the view is rendered.
@FernandoCamargo is Right, this library is old and should be updated with better caching... here is the new library with better performance github.com/MarsVard/IonIconView
j
j7nn7k

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.


T
Tower Jimmy

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

P
Pouya Danesh

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.