Lucas Borges Lucas Borges - 6 months ago 31
Android Question

How to change a single menu item text size

I have this piece of code in my menu.xml, which is inside a navigation view:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group>
<item
android:title="Blue"
android:id="@+id/blue">
<menu>
<item
android:id="@+id/red"
android:title="Red"
/>
</menu>
</item>
</group>
<group>
<item
android:id="@+id/green"
android:title="Green" />
<item
android:id="@+id/yellow"
android:title="Yellow"/>
</group>
</menu>


I want to change only the blue item text size. How can I do that?

Answer

When you create your menu, you can change the size of your text like this:

public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater awesome = getMenuInflater();
    awesome.inflate(R.menu.menu_main, menu);
    for(int i = 0; i < menu.size(); i++) {
        MenuItem item = menu.getItem(i);
        if (item.getItemId() == R.id.blue)
        {
            SpannableString spanString = new SpannableString(menu.getItem(i).getTitle().toString());
            int end = spanString.length();
            spanString.setSpan(new RelativeSizeSpan(1.5f), 0, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            item.setTitle(spanString);
        }
    }
    return true;
}
Comments