简体   繁体   中英

How to set the font awesome icons in menu items in android?

在此输入图像描述 I am facing the issue in font awesome ,i tried many ways to set the font awesome icon in menu items but the problem is not solved.

   @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.drawer_menu, menu);
    return true;
}


@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    TextDrawable faIcon = new TextDrawable(this);
    faIcon.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
    faIcon.setTextAlign(Layout.Alignment.ALIGN_NORMAL);
    faIcon.setTypeface(FontAwesomeManager.getTypeface(this, FontAwesomeManager.FONTAWESOME));
    faIcon.setText(getResources().getText(R.string.home_font));
    MenuItem menuItem = menu.findItem(R.id.home);
    menuItem.setIcon(faIcon);
    menuItem.setTitle("Home");
    return  true;
}

The above code is my font awesome code for setting the font awesome as menu items icon in navigation drawer menu .Please help me how to solve this.

How to add the font awesome font in menu items like shown in above image.

This exception is shown in logcat ..java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference

You should get a reference to Menu from either onCreateOptionsMenu(Menu) , or onPrepareOptionsMenu(Menu) callbacks.

@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
    MenuItem menuItem = menu.findItem(R.id.alerts_id);
    ... // other actions with menuItem
}

I also encountered the same issue and if somebody is still struggling with this scenario, can try the following way to see if it works for them

  1. As the navigation menu items are found in Navigation view, we have to search for NavigationView in onCreateOptionsMenu like below

NavigationView navigationView = findViewById(R.id.nav_view); Menu navMenu = navigationView.getMenu();

  1. I am using a custom Drawable class, "FontDrawable", next step is to initialize an instance of FontDrawable, set the Font Awesome icon, and set its size

FontDrawable drawable = new FontDrawable(this, R.string.fa_sign_out_alt_solid, true, false); drawable.setTextSize(20);

  1. Find your menu item inside navigation menu

MenuItem logOutItem = navMenu.findItem(R.id.nav_logout);

  1. Set icon to menu item

logOutItem.setIcon(drawable);

Screenshot is shown below for reference

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM