2016-04-15 53 views
3

我正在以編程方式將菜單項添加到菜單中。我想添加選擇背景顏色到特定的項目。我如何添加背景到menuItem?如何更改android中menuItem的背景顏色?

enter image description here

你的回答將不勝感激。

+0

這個答案可能有幫助:http://stackoverflow.com/questions/19659637/how-to-change-the-background-color-of-action-bars-option-menu-in-android-4-2 – davehenry

+0

請檢查http://stackoverflow.com/a/28979152/3790150 – saeed

回答

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"> 
      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> 
2

而其他的答案提供改變風格(這將影響所有菜單項,並按照我的理解,需要的是改變一個菜單項),
我建議你使用android:actionLayout屬性來實現自定義爲菜單項目佈置。

查看documentation(查找actionLayout實際上很簡單)。

此外,我認爲有可能使selector作爲您的佈局和使用它。


更新。對不起,我誤導你:(

如果菜單項顯示爲行動(而不是在三個點壓時),所有這一切都只會工作

好像給其他的答案是正確的傢伙 - 自定義此的唯一途徑正在改變的主題

但請thisthis - 。它可以幫助你爲你的目的提供選擇
你也可以創建PopupMenu甚至PopupWindow,最後一個是完全可定製的
的最後一個選項是創建自定義微調,檢查this

希望從這件事可以幫助你。謝謝。

+0

你是對的,你能解釋如何將actionlayout添加到menuItem以編程方式android – Vasant