Search code examples
androidmaterial-designandroid-toolbarmaterial-components-androidmaterial-components

popup menu background color change not working


i am begineer in android. I want to popup menu background color change.I try this code for background color change but its not working for me.i don't know why not working this code.

<!--popup menu item style-->
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.MaterialComponents.Light">
    <item name="android:textColor">@color/colorWhite</item>
    <item name="android:popupBackground">@color/colorBlack</item>
    <item name="actionOverflowMenuStyle">@style/CMOptionsMenu</item>
    <item name="android:divider">@color/colorWhite</item>
    <item name="android:dividerHeight">1dp</item>
</style>
<style name="CMOptionsMenu" parent="Widget.AppCompat.PopupMenu.Overflow">
    <item name="android:popupBackground">@color/colorBlack</item>
    <item name="overlapAnchor">false</item>
    <item name="android:divider">@color/colorRegisterHeader</item>
    <item name="android:dividerHeight">1dp</item>
</style>

//this activity code for popup menu

            PopupMenu popup = new PopupMenu(HomeActivity.this, v);
            popup.setOnMenuItemClickListener(HomeActivity.this);
            popup.inflate(R.menu.popup_menu);

Solution

  • You can customize the background color using the android:popupBackground attribute.

      <!-- Popup Menu -->   
      <style name="MyPopup" parent="@style/Widget.MaterialComponents.PopupMenu">
        <item name="android:popupBackground">@color/custom</item>
      </style>
    

    You can configure globally this style in your app theme using the popupMenuStyle attribute:

      <!-- Base application theme. -->
      <style name="AppTheme" parent="Theme.MaterialComponents.Light">
         ....
        <item name="popupMenuStyle">@style/MyPopup</item>
      </style>
    

    Just use:

    PopupMenu popup = new PopupMenu(this, anchor);
    popup.getMenuInflater().inflate(R.menu.custom_menu, popup.getMenu());
    popup.show();
    

    Currently PopupMenu uses colorOnPrimary to define the textColor. To change it you have to define a textAppearance:

      <style name="MytextAppearanceLargePopupMenu" parent="@style/TextAppearance.MaterialComponents.Subtitle1">
        <item name="android:textColor">@color/colorAccent</item>
      </style>
    

    and then in your app theme adding this attribute:

      <!-- Base application theme. -->
      <style name="AppTheme" parent="Theme.MaterialComponents.Light">
        <item name="textAppearanceLargePopupMenu">@style/MytextAppearanceLargePopupMenu</item>
      </style>