要自定义 Android PopupMenu 的背景,您可以创建一个自定义的样式并将其应用于 PopupMenu。以下是一种方法:
<style name="PopupMenuStyle" parent="@android:style/Widget.Holo.Light.PopupMenu">
<item name="android:popupBackground">@drawable/custom_popup_background</item>
</style>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FF0000" /> <!-- 设置背景颜色 -->
<corners android:radius="10dp" /> <!-- 设置圆角半径 -->
</shape>
PopupMenu popupMenu = new PopupMenu(context, view);
try {
Field mPopup = PopupMenu.class.getDeclaredField("mPopup");
mPopup.setAccessible(true);
Object menuPopupHelper = mPopup.get(popupMenu);
Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
} catch (Exception e) {
e.printStackTrace();
}
popupMenu.getMenuInflater().inflate(R.menu.menu_main, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
//处理菜单项的点击事件
return true;
}
});
popupMenu.show();
这样就可以自定义 Android PopupMenu 的背景了。您可以根据需要调整样式和背景图像来实现不同的效果。