With the new NavigationView
, we are able to set a drawer's items through a menu resource in XML.
With that, we can set each item with something like
<item
android:id="@+id/drawer_my_account"
android:icon="@drawable/ic_my_account"
android:title="@string/drawer_my_account" />
But now, I want to set a custom typeface to each of those items in my drawer, and I could not find a way to do that, either by XML or by Java code. Is there a way to do it?
A different way to set your custom font:
1. You can add your fonts in a "font" folder, and then you can use them in any TextView (or wherever you needed)
An example of font.xml:
2. In your styles.xml file, you can customize your item text style with that font, and color, wherever you need (from @Moonis Abidi answer)
3. Now, you only have to specify this in your navigation view with app:itemTextAppearance:
// ------------- Also, if you need to use this font from others TextViews, you can use it like
Yes. The
NavigationView
doesn't provide a direct way of handling this, but it can easily be achieved usingView.findViewsWithText
.There are two things that will help us handle this.
MenuItem
view is aTextView
. So, that makes applying yourTypeface
that much easier. For more information on theTextView
actually used byNavigationView
, seeNavigationMenuItemView
.NavigationView
provides a callback when aMenuItem
is selected. We're going to have to supply eachMenuItem
with a unique id and this callback will help generify those ids as much as possible, which means a little less code later on. Although, this is more related to whether or not you have aSubMenu
.Implementation
Notice each
MenuItem
id is simplymenuItem+Position
. This will come in handy later when we're finding theView
for eachMenuItem
.You can see how using a generic
MenuItem
id allows you to utilizeResources.getIdentifier
and save a few lines of code.SubMenu
caveatSomething to keep in mind. You need to explicitly loop over your
N
menu items rather than usingMenu.size
. Otherwise, yourSubMenu
items won't be recognized. In other words, if you don't have aSubMenu
, another way of doing this would be:And you don't have to worry about applying a unique id to each
MenuItem
.Results
The font I'm using in the example is: Smoothie Shoppe
for those who use @Moinkhan answer, for applying font to every part of your menus use that solution and for every header section use id. your menu like this..
and solution like this..
maybe it helps someone.
This is another approach:
A NavigationView has children called NavigationMenuItemView. A NavigationMenuItemView has two children. One is AppCompatCheckedTextView.
Override onLayout method of the NavigationView like bellow and change Typefase of the AppCompatCheckedTextView: