Android更改popupmenu背景並顯示圖標
阿新 • • 發佈:2018-08-03
light add 成了 view 參數傳遞 *** .sh this google
似乎popupmenu是無法單獨設置style的,好像是由context決定的,前幾天需要設置style,找了很久才找一一個辦法,似乎是通過 ContextThemeWrapper 包裝一個 Context 然後把 Context 作為參數傳遞給popupmenu的構造函數
java代碼如下
/**************************************************************************/ Context wrapper = new ContextThemeWrapper(this, R.style.MyPopupStyle); /**************************************************************************/ PopupMenu popupMenu = new PopupMenu(wrapper, view); popupMenu.getMenuInflater().inflate(R.menu.user_main_toolbar_add_items, popupMenu.getMenu()); popupMenu.show();
style文件如下
<style name="MyPopupStyle" parent="Widget.AppCompat.PopupMenu"> <item name="android:itemBackground">@drawable/toolbar_item_selector</item> <item name="android:textColor">@color/whitesmoke</item> </style>
記得當時使用background屬性是無效的,改成了itembackground才有了效果
而且為了使popupmenu可以顯示icon,找了一種方法,並沒有去查原因,僅僅是用了,代碼如下
/**************************************************************************/ Context wrapper = new ContextThemeWrapper(this, R.style.MyPopupStyle); /**************************************************************************/ PopupMenu menu = new PopupMenu(wrapper, view); menu.inflate(R.menu.user_main_toolbar_add_items); MenuPopupHelper menuHelper = new MenuPopupHelper(wrapper, (MenuBuilder) menu.getMenu(), view); menuHelper.setForceShowIcon(true); menuHelper.show();
而且官方文檔好像沒搜到這個類,谷歌第一條是源代碼,裏面有各個方法的說明,包括setForceShowIcon,
本文本來只用來自己參考的,不過可能會有人看到,還是貼出鏈接,可以看下
MenuPopupHelper。java
Android更改popupmenu背景並顯示圖標