Search code examples
androidbackgroundstylespopupmenu

Android change background color of popup menu


I don't understand why is so painful to change a color for an android app. I tried several ways to change the background color of the popup menu in my action bar with no success.

I'm using a AppTheme.NoActionBar to style, obviously, the action bar.

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="navigationIcon">@drawable/ic_return_dark</item>
    <item name="overlapAnchor">false</item>
    <item name="popupMenuStyle">@style/PopupMenu</item>
</style>

<style name="PopupMenu" parent="Widget.AppCompat.PopupMenu">
    <item name="android:popupBackground">@color/color4</item>
</style>

Following the examples that I found, there was this explanation that you need to insert in your custom style (in my case AppTheme.NoActionBar) a custom popupMenuStyle in order to custom the popupBackground, which changes the background color of popup menu. It doesn't work.

enter image description here

What can I do to change the background color of popup menu?


Solution

  • To change the color of the Options Menu in Android, changing themes and styles won't help. You have to initialise LayoutInflater Factory Class.

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
       MenuInflater inflater = getMenuInflater();
       inflater.inflate(R.menu.my_menu, menu);
       getLayoutInflater().setFactory(new Factory() {
       @Override
       public View onCreateView(String name, Context context,
       AttributeSet attrs) {
       if (name .equalsIgnoreCase(“com.android.internal.view.menu.IconMenuItemView”)) {
       try {
       LayoutInflater f = getLayoutInflater();
       final View view = f.createView(name, null, attrs);
       new Handler().post(new Runnable() {
       public void run() {
    
       view.setBackgroundResource(R.drawable.your_color);
    
       ((TextView) view).setTextColor(Color.your_color);
       }
       });
       return view;
       } catch (InflateException e) {
       } catch (ClassNotFoundException e) {
       }
       }
       return null;
       }
       });
       return super.onCreateOptionsMenu(menu);
       }