7

I'm just learning android so sorry for my lack of knowledge on the subject. I mainly work as a Web Developer and we use Font Awesome all the time so I was trying to get it to work with Android. I first found out I could use font awesome here. With some deeper searching I found out how to put a font awesome icon in the action menu bar in the title here. I am missing out on having the ability to have backup text when there is room by setting the title instead of the icon and the title.

I was wondering if I could set the icon in font awesome instead of the title and just have normal descriptive text for the title. It wants a drawable or drawable resource id when I do the setIcon method on the menu-item. Could I convert it to a drawable? What is the best way to approach keeping font awesome for the icon and having both the icon and title? Any help or direction is appreciated.

So I have the following code in my main activity:

public class MainActivity extends AppCompatActivity {

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // https://stackoverflow.com/a/32780748/2066736
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.drawable.redbird_webkit_onwht);
        getSupportActionBar().setDisplayUseLogoEnabled(true);

        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);

        setFontAwesomeMenuItem(menu, R.string.icon_calendar, R.id.action_calendar);
        setFontAwesomeMenuItem(menu, R.string.icon_search, R.id.action_search);
        setFontAwesomeMenuItem(menu, R.string.icon_plus, R.id.action_new_post);

        // menu.add(0, MENU_ITEM_LOGOUT, 102, R.string.logout);

        return true;
    }

    private void setFontAwesomeMenuItem (Menu menu, int rIdString, int rIdIdOfElement) {
        SpannableString s = new SpannableString(getString(rIdString));
        s.setSpan(new TypefaceSpan(this, "fontawesome-webfont.ttf"), 0, s.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        menu.findItem(rIdIdOfElement).setTitle(s);
    }
}

And I got the following TypefaceSpan class from here:

/**
 * Style a {@link Spannable} with a custom {@link Typeface}.
 *
 * @author Tristan Waddington
 * copied from https://stackoverflow.com/a/15181195/2066736
 */
public class TypefaceSpan extends MetricAffectingSpan {
    /** An <code>LruCache</code> for previously loaded typefaces. */
    private static LruCache<String, Typeface> sTypefaceCache =
            new LruCache<String, Typeface>(12);

    private Typeface mTypeface;

    /**
     * Load the {@link Typeface} and apply to a {@link Spannable}.
     */
    public TypefaceSpan(Context context, String typefaceName) {
        mTypeface = sTypefaceCache.get(typefaceName);

        if (mTypeface == null) {
            mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                    .getAssets(), String.format("fonts/%s", typefaceName));

            // Cache the loaded Typeface
            sTypefaceCache.put(typefaceName, mTypeface);
        }
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }
}
Community
  • 1
  • 1
John
  • 7,114
  • 2
  • 37
  • 57

2 Answers2

10

Answer is late but for future visitors there is a great library for working with font awesome in android called iconify written by JoanZapata. You can find it here

After library being corectly initialized you can do something like this with your ActionBar menu item:

<menu xmlns:android="http://schemas.android.com/apk/res/android"

   <item
       android:id="@+id/item_menu
       showAsAction="always"
       android:title="@string/title"/>

</menu>

and from java code you only need to do something like this:

 menu.findItem(R.id.item_menu).setIcon(
    new IconDrawable(this, FontAwesomeIcons.fa_share)
    .colorRes(R.color.ab_icon)
    .actionBarSize());

Hope this would help someone :) Ask, if you have any questions:)

Community
  • 1
  • 1
Karol Żygłowicz
  • 2,442
  • 2
  • 26
  • 35
  • 1
    I am getting this error: Unable to find the module associated with icon fa-barcode, have you registered the module you are trying to use with Iconify.with(...) in your Application? How can I solve this? Do I need to add anything other than compile 'com.joanzapata.iconify:android-iconify-fontawesome:2.2.2' line in the build.gradle? – Vincy Apr 10 '17 at 16:57
  • 1
    @Vincy Yes. You need to init the library `Iconify.with(new FontAwesomeModule())...` as shown in documentation, just below the `public class MyApplication extends Application {...` block. Create class extending Aplication Here is example how to extend the Application class https://www.intertech.com/Blog/androids-application-class/ . The important thing is to register it in manifest: `android:name="YourApplicationClassName"` inside tag – Karol Żygłowicz Apr 10 '17 at 20:01
  • Thank you for the quick response Karol Zyglowicz. It worked like a charm! I missed the Iconify.with(new FontAwesomeModule())... part and the moment I added it, I was in the moon! LOL! Thank you very much!!! – Vincy Apr 11 '17 at 10:33
  • Now, I need it in while color and this is what I have done in my code but it draws as black... menu.findItem(R.id.menuBarcodeScanner).setIcon(new IconDrawable(this, FontAwesomeIcons.fa_barcode) .colorRes(R.color.white) .actionBarSize() .color(R.color.white) ); What am I doing wrong or missing? – Vincy Apr 11 '17 at 10:35
  • have you declared your `#ffffff` in your `colors.xml`? This should work because the icon is showing, so it's probably your's code related bug. Maybe you overwrote this in `styles.xml` or something... I'm not able to find mistake remotly :( – Karol Żygłowicz Apr 11 '17 at 10:58
  • Yes, but did not take it but I had to change my code like this and then it worked but very strange though... IconDrawable iconDrawable = new IconDrawable(this, FontAwesomeIcons.fa_barcode) .actionBarSize(); iconDrawable.color(Color.WHITE); iconDrawable.colorRes(R.color.white); menu.findItem(R.id.menuBarcodeScanner).setIcon(iconDrawable); – Vincy Apr 11 '17 at 12:15
  • Iconify is no longer maintained – Fernando Torres Oct 01 '19 at 00:25
5

Please check this:

TextDrawable faIcon = new TextDrawable(this);
faIcon.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
faIcon.setTextAlign(Layout.Alignment.ALIGN_CENTER);
faIcon.setTypeface(FontAwesomeManager.getTypeface(this, FontAwesomeManager.FONTAWESOME));
faIcon.setText(getResources().getText(R.string.fa_android));
Menu menu = (Menu) findViewById(R.id.menu);
MenuItem menuItem = menu.findItem(R.id.menu_item);
menuItem.setIcon(faIcon);

You can get TextDrawable class from here

Source

Divya
  • 543
  • 2
  • 13
  • 20
  • 2
    This is great, cause no need to import other libs + works not only for Fontawesome, but also for my custom made fonts, like mine custom made icomoon fonts. – Andris Nov 08 '19 at 08:05