Android: self-defined PopupMenu style (Display icon/set RadioButton icon)

Source: Internet
Author: User

PopupMenu is a very lightweight component in Android. Compared with Popupwindow, PopupMenu's ability to define itself is smaller, but it is more convenient to use.

First on:



The following features are implemented in this example:

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

The default state. The icon for PopupMenu is not displayed. And Android is not open for us no matter what API to set its display status. In order to display the icon of a menu item, you can rewrite the PopupMenu and change the related attributes, and 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 group the item in the resource file in menu.

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, which indicate radio, check, and not selectable.


3. Define your own 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.

<!--define 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>
At the same time, 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. But 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:

/** * Own Definition 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.            Force Display 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: self-defined PopupMenu style (Display icon/set RadioButton icon)

Related Article

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.