0

Is it possible on Android to have MenuItems (either the ones from the options menu hardware key or action bar -- they are the same anyways) with different styles?

I want one to have a selector applied and another with different selector.

From my search online, I found that you can change the theme and override an attribute with your own style, but that applies to ALL MenuItems.

Can I still set the android:background property in XML?

Zyoo
  • 773
  • 10
  • 30
dnkoutso
  • 6,041
  • 4
  • 37
  • 58

2 Answers2

2

It is possible for items of the ActionBar. You have to define the item that you want to have a different selector as a custom action view.

<item
    android:id="@+id/menu_custom"
    android:actionLayout="@layout/action_view"
    android:showAsAction="always"/> 

In the layout referenced by android:actionLayout you have an ImageView that you assign your selector and make it clickable and focusable.

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/action_view_background"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:minWidth="56dip"
    android:paddingBottom="8dip"
    android:paddingTop="8dip"
    android:src="@drawable/ic_launcher" />

The click event is not handled by onOptionsItemSelected. You have to attach an OnClickListener in onCreateOptionsMenu.

menu.findItem(R.id.menu_custom).getActionView().setOnClickListener(l);
Matthias Robbers
  • 15,689
  • 6
  • 63
  • 73
1

Quoting this answer

According to the official document at http://developer.android.com/guide/topics/ui/menus.html#checkable

Note: Menu items in the Icon Menu (from the Options Menu) cannot display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, you must manually indicate the checked state by swapping the icon and/or text each time the state changes.

The same is applied to action bar items, since it's the same object, MenuItem

Community
  • 1
  • 1
Robert Estivill
  • 12,369
  • 8
  • 43
  • 64
  • I was not referring to checkable or not, but this might lead me to the answer. Care to post some code sample? – dnkoutso Jan 05 '13 at 16:53
  • What it means with checkable or not, is that MenuItem's doesn't have a internal state that can be represented by a selector. Because of this, you have to manually keep track if the button was pressed or not and change the icon accordingly. – Robert Estivill Jan 05 '13 at 16:55