要自定義 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 的背景了。您可以根據需要調整樣式和背景圖像來實現不同的效果。