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

戏子无情 提交于 2019-12-11 08:18:22

问题


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.


回答1:


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
}



回答2:


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



来源:https://stackoverflow.com/questions/41606787/how-to-set-the-font-awesome-icons-in-menu-items-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!