Android: Custom PopupMenu Style (Display icon/set RadioButton icon)

Source: Internet
Author: User

PopupMenu is a very lightweight component in Android. Compared to Popupwindow, PopupMenu's customizable capabilities are small, but easier to use.

First on:



The following functions are implemented in this example:

1. Force the icon for the menu item to appear.

By default, the PopupMenu icon is not displayed, and Android does not open any APIs for us to set its display status. To display the icon for a menu item, you can rewrite the popupmenu yourself and modify the related properties, or you can use reflection directly:

try {            Field field = Popupmenu.getclass (). Getdeclaredfield ("Mpopup");            Field.setaccessible (true);            Menupopuphelper Mhelper = (menupopuphelper) field.get (popupmenu);            Mhelper.setforceshowicon (True);        } catch (Illegalaccessexception | Nosuchfieldexception e) {            e.printstacktrace ();        }
2. Add a radio/Check button to the menu item: Use the group tag to add a group to item in the resource file for menus.

Menu_popup.xml:

<menu xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:app= "http://schemas.android.com/apk/ Res-auto "> <group android:checkablebehavior=" single "> <item android:id=" @+id/menu_setting _wifi "android:title=" using WiFi "android:orderincategory=" "android:icon=" @drawable/menu_s            Etting_wifi "app:showasaction=" Ifroom "/> <item android:id=" @+id/menu_setting_gps "            Android:title= "Using GPS" android:orderincategory= "android:icon=" @drawable/menu_setting_gps " app:showasaction= "Ifroom"/> </group> <group> <item android:id= "@+id/            Menu_setting_usericon "android:title=" set Avatar "android:icon=" @drawable/menu_setting_usericon " android:orderincategory= "app:showasaction=" "Never"/> </group></menu>
Among them, Checkablebehavior has 3 values to choose from: Single,all,none, respectively, for radio, check, and not selectable.
3. Customize the icon for the above radio/check button.

PopupMenu inherits styles from the current context, so you can control the style of the PopupMenu by setting the activity's style.

<!--Customize the style of RadioButton on PopupMenu-<style name= "Popupmenustyle" parent= "Apptheme"    >        <item Name= "Android:radiobuttonstyle" > @style/menuradiobuttonstyle</item>    </style>    <style Name= "Menuradiobuttonstyle" parent= "@android: Style/widget.compoundbutton.radiobutton" >        <item name= " Android:button "> @drawable/selector_menu_rb</item>    </style>
Also add a style to the activity that PopupMenu belongs to in manifest:
<activity            android:name= ". Popupmenuactivity "            android:theme=" @style/popupmenustyle "/>

Add: You can also set the style directly when the initial session PopupMenu. However, this way the compiler will appear multiple times with a warning: Too many attribute references. Therefore, it is not recommended.

Context wrapper = new Contextthemewrapper (activity, R.style.popupmenustyle); PopupMenu PopupMenu = new PopupMenu (activity, ancher);

======  ======

Activity Section Complete code:

/** * Custom PopupMenu * Created by Hanj on 15-3-17.        */public class Popupmenuactivity extends Activity {@Override protected void onCreate (Bundle savedinstancestate) {        Super.oncreate (savedinstancestate);        LinearLayout lin = new LinearLayout (this);        Button btn = New button (this); Linearlayout.layoutparams p = new Linearlayout.layoutparams (LinearLayout.LayoutParams.WRAP_CONTENT, Linear        Layout.LayoutParams.WRAP_CONTENT);        Btn.setlayoutparams (P);        Lin.addview (BTN);        Btn.settext ("show PopupMenu");                Btn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            ShowPopupMenu (Popupmenuactivity.this, v);        }        });    Setcontentview (Lin);    }//The ID of the currently selected MenuItem private int checkeditemid = R.id.menu_setting_wifi; private void ShowPopupMenu (final context context, View Ancher) {PopupMenu PopupMenu = new PopupMenu (Context, anche    R);    Introduction of Menu Resource Popupmenu.inflate (r.menu.menu_popup);        Set the check Popupmenu.getmenu (). FindItem (Checkeditemid). Setchecked (True);            Monitor Popupmenu.setonmenuitemclicklistener for menu items (new Popupmenu.onmenuitemclicklistener () {@Override                    public boolean Onmenuitemclick (MenuItem MenuItem) {switch (Menuitem.getitemid ()) {                        Case r.id.menu_setting_wifi:checkeditemid = R.id.menu_setting_wifi;                        Toast.maketext (Context, "WIFI", Toast.length_short). Show ();                    Break                        Case r.id.menu_setting_gps:checkeditemid = R.id.menu_setting_gps;                        Toast.maketext (Context, "GPS", Toast.length_short). Show ();                    Break                        Case R.id.menu_setting_usericon:toast.maketext (Context, "User_icon", Toast.length_short). Show ();            Break    } return true;        }        });            Use reflection to force the display of the menu icon try {Field field = Popupmenu.getclass (). Getdeclaredfield ("Mpopup");            Field.setaccessible (TRUE);            Menupopuphelper Mhelper = (menupopuphelper) field.get (PopupMenu);        Mhelper.setforceshowicon (TRUE); } catch (Illegalaccessexception |        Nosuchfieldexception e) {e.printstacktrace ();    }//Display PopupMenu popupmenu.show (); }}








Android: Custom PopupMenu Style (Display icon/set RadioButton icon)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.