Android - How to make a menu item disabled but remove the default grey text colour?

354 views Asked by At

My menu file menu_main.xml, the "Create" item is just a title, so it should be disabled.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.amazon.device.controllermanager.docsuilocal.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />

    <item
        android:icon="@drawable/ic_add"
        android:title="@string/menu_create"
        app:showAsAction="always">
        <menu>
            <group android:id="@+id/sorting" >
                <item
                    android:id="@+id/title"
                    android:title="Create"
                    app:showAsAction="never" />
            </group>
            <item
                android:id="@+id/action1"
                android:title="Document"
                app:showAsAction="never" />
            <item
                android:id="@+id/action2"
                android:title="Spreadsheet"
                app:showAsAction="never" />
            <item
                android:id="@+id/action3"
                android:title="Presentation"
                app:showAsAction="never" />

        </menu>
    </item>
</menu>

The id @id/title is just a title, hence it shouldn't be clickable, but it should be bold in color, so I do this in my java code

@Override
public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.menu_main, menu);
  MenuItem createItem = menu.findItem(R.id.title);
  SpannableString spanString = new SpannableString(createItem.getTitle().toString());
  spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
  createItem.setTitle(spanString);
  createItem.setCheckable(false);
  createItem.setEnabled(false);
  MenuCompat.setGroupDividerEnabled(menu, true);
  return true;
}

The problem is it gets the grey disabled colour, but I want it have bold text and to not be clickable, as its purpose is to act like a title.

Anyway I could overwrite the grey colour in this particular menu item alone?

1

There are 1 answers

0
Zain On

You can add one more span to the spanString to se the foreground color using ForegroundColorSpan:

spanString.setSpan(new ForegroundColorSpan(ResourcesCompat
                                           .getColor(resources, R.color.gray, null)), 
                                                            0, spanString.length, 0);

The color value is <color name="gray">#606060</color>