Search code examples
android-studiokotlinandroid-navigationview

How to change the font and the size of a NavigationView menu item?


I'm trying to change the font and the size of the first element in my NavigationView programmatically . I thought I could do something like this:

nav.menu.findItem(R.id.nav_user).textSize = ...
nav.menu.findItem(R.id.nav_user).textFont = ...

but it seems that I can't or I don't know how. Any help?


Solution

  • You can use a SpannableString:

    val item: MenuItem = nav.menu.findItem(R.id.nav_user)
    val spannableString = SpannableString(item.title.toString())
    spannableString.setSpan(RelativeSizeSpan(1.5f), 0, spannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannableString.setSpan(TypefaceSpan("font_name"), 0, spannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    item.title = spannableString
    

    the RelativeSizeSpan value 1.5f is a relative and not absolute value for the text size, so adjust it as you wish.