1

I've implemented a application where action bar menu items background colors needs to be dynamic. I know that we can change action bar color dynamically by using the following code. But it is not working for action bar menu items. Please help me on this.

ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable("COLOR")); 

enter image description here

Ramesh
  • 1,252
  • 3
  • 12
  • 30

2 Answers2

1

You have said that the background colors need to be dynamic. A couple of points:

  1. According to the docs (link):

If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)

  1. MenuInflater ignores the tags in the layout resource that try to modify the menu appearance except for the title and icon.

So, as long as the appearance of the menu item is dictated by the app theme (which can be applied to the entire menu and not to individual items) my suggestion is to use predefined styles like this:

<style name="RedDropDownTheme" parent="AppBaseTheme">
    <item name="android:dropDownListViewStyle">@style/RedDropDownListView</item>
</style>

<style name="RedDropDownListView" parent="android:style/Widget.Holo.ListView.DropDown">
    <item name="android:background">@color/your_red_color</item>
</style>

And if you need to change the color afterwards you would have to save the new color choice in shared preferences, call activity's recreate() method, and apply the new theme (setTheme(R.style.different_color_style)) in activity's onCreate() based on the value in shared prefs.

dev.bmax
  • 8,998
  • 3
  • 30
  • 41
0

I think the easiest solution would be to set a drawable as background for the action bar, you could create a simple shape. Then dynamically change the drawable background.

Here is how to dynamically add a drawable as background

Here how to dynamically change drawable color.

Hope this helps, Regards Jose

Community
  • 1
  • 1
Jose Gonzalez
  • 1,491
  • 3
  • 25
  • 51