Search code examples
androidandroiddesignsupportnavigationviewandroid-navigationviewandroid-selector

Adding font size to NavigationView item in android


In navigationView when i select an item, the selected item should be in bold and increase in font size. How do i achieve this?

Basically, I want to add a selector for the navigation item which will display bold font on selected state and normal font on non-selected state.

Thanks


Solution

  • Try like below

        //put this in main Activity
    private void setFontToMenuItem(MenuItem mi) {
    
        Typeface font = Typeface.createFromAsset(getAssets(), "fonts/customfont.ttf");
        SpannableString mNewTitle = new SpannableString(mi.getTitle());
        mNewTitle.setSpan(new CustomTypefaceSpan("" , font), 0 , mNewTitle.length(),  Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        mi.setTitle(mNewTitle);
    }
    

    Use like this

    navigationView = (NavigationView) findViewById(R.id.navigation_view);
        Menu m = navigationView.getMenu();
        for (int i=0;i<m.size();i++) {
            MenuItem item = m.getItem(i);
    
            //for aapplying a font to subMenu ...
            SubMenu subMenu = item.getSubMenu();
            if (subMenu!=null && subMenu.size() >0 ) {
                for (int j=0; j <subMenu.size();j++) {
                    MenuItem subMenuItem = subMenu.getItem(j);
                    setFontToMenuItem(subMenuItem);
                }
            }
    
            //the method we have create in activity
            setFontToMenuItem(item);
        }