mallaudin mallaudin - 21 days ago 7
Android Question

Change Popup menu background color


NOTE: I have searched for an hour and tried all solutions already provided
by stackoverflow.


I am studying theme overlays. I have made a sample app, which opens a popup menu on clicking an action bar icon. Here is my
styles.xml


<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>

</style>

<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>



<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Light">
<item name="android:textColorPrimary">@color/colorAccent</item>
</style>

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Dark">
<!-- added all to see which one will work.-->
<item name="android:popupMenuStyle">@style/PopupMenu</item>
<item name="android:itemBackground">@color/colorAccent</item>
<item name="android:colorBackground">@color/colorAccent</item>

</style>

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

</resources>


and here is my toolbar style.

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"/>

</android.support.design.widget.AppBarLayout>


I have set the
popupTheme
to the one I have in my
styles.xml
. Now I want to change the background color of popup menu, which is currently white.

enter image description here

Here is the code.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

if(item.getItemId() == R.id.standard_menu){
showPopupMenu(item);
return true;
}
return super.onOptionsItemSelected(item);
}

private void showPopupMenu(MenuItem item) {
PopupMenu p = new PopupMenu(this, findViewById(item.getItemId()));
p.inflate(R.menu.pop_menu);
p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this, "clicked.", Toast.LENGTH_SHORT).show();
return true;
}
});
p.show();
}

Answer

This worked for me

<item name="android:itemBackground">@color/primary</item>

Insert that into your main style I hope this works for you