3

I am working on programmatically add a menu-Item into menu. I want to add background color on selection to particular Item. How can I add background to menuItem?

enter image description here

Your answer would be appreciated.

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
Vasant
  • 3,475
  • 3
  • 19
  • 33
  • This answer might help: http://stackoverflow.com/questions/19659637/how-to-change-the-background-color-of-action-bars-option-menu-in-android-4-2 – davehenry Apr 15 '16 at 09:04
  • please check http://stackoverflow.com/a/28979152/3790150 – saeed Apr 15 '16 at 09:05

2 Answers2

3

While other answers provide change style (which will affect all menu items, and, as I understand, need is to change one menu item),
I propose you to use android:actionLayout attribute to implement your custom layour for menu item.

See documentation for it (search actionLayout there, it's very simple actually).

Also I think there is a possibility to make a selector as your layout and use it.


Update. Sorry, I mislead you :(

All of this will work only if MenuItem is shown as Action (not when pressing on three dots).

Seems like guys given other answers were right - the only way to customize this is changing themes.

But please check this and this - it might help you to provide selector for your purpose.
Also you can create PopupMenu or even PopupWindow, last one is fully customizable.
The last option is to create custom Spinner, check this.

Hope something from this will help you. Thanks.

Community
  • 1
  • 1
Goltsev Eugene
  • 3,325
  • 6
  • 25
  • 48
  • you are right,can you explain how to add actionlayout into menuItem programmatically android – Vasant Apr 15 '16 at 10:10
1

Firstly You need to create an Style for popmenu as you want refer below sample for that

<style name="MyApp.PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
    <item name="android:textStyle">@style/commonEditTextTheme</item>
    <item name="android:popupBackground">@drawable/pop_up_menu_bg_with_shadow</item>
</style>

Place of drawable you can also replace with color as you needed or make XML Drawable into your drawable folder

<style name="commonEditTextTheme" parent="@android:style/TextAppearance.Medium">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

this pop menu theme add in your main application or activity theme like below

<!--My Theme-->
<style name="MyTheme" parent="@android:style/Theme.Holo.Light">
    ......
    <item name="android:popupMenuStyle">@style/MyApp.PopupMenu</item>
</style>
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
Rohitashv jain
  • 244
  • 1
  • 15