Android uses Popupwindow to bring up more menus

Source: Internet
Author: User
Tags border color gettext set background

Recently want to do a popup more menu, and the original pop-up menu is not the effect we want, so it is necessary to customize the menu. I also learn from the information on the web for encapsulation, it feels pretty good.

Native menus such as:


After customization:


is not seen here after the contrast, the original effect is not ideal, so still define it yourself!

1, Popupwindow can be said to be a floating on the activity of the container, usually used to display a custom view. Package Popmenumore for pop-up menus

/** * Package for pop-up menus. * http://blog.csdn.net/maosidiaoxian/article/details/39178167 * AUTHOR:MSDX ([email protected]) * TIME:14-6-13     PM 1:51 */public class Popmenumore {/** * context.    */Private Context mcontext;    /** * Menu item */private arraylist<popmenumoreitem> mitemlist;     /** * List adapter.    */Private Baseadapter madapter;     /** * Menu Select Listen.    */Private Onitemselectedlistener Mlistener;    /** * Lower Corner icon */private ImageView Cornericon;     /** * list.    */Private ListView Mlistview;     /** * pop-up window.    */Private Popupwindow Mpopupwindow;        Public Popmenumore (Context context) {Mcontext = context;        Mitemlist = new arraylist<> ();        View view = Oncreateview (context);        View.setfocusableintouchmode (TRUE);        Madapter = Oncreateadapter (context, mitemlist);        Cornericon = Findcornerview (view);        Mlistview = findListView (view);        Mlistview.setadapter (Madapter); Mlistview. Setonitemclicklistener (New Adapterview.onitemclicklistener () {@Override public void Onitemclick (Ad Apterview<?> Parent, view view, int position, long ID) {Popmenumoreitem item = (Popmenumoreitem) mAd                Apter.getitem (position);                if (Mlistener! = null) {mlistener.selected (view, item, position);            } Mpopupwindow.dismiss ();        }        });  View.setonkeylistener (New View.onkeylistener () {@Override public boolean onKey (View v, int keycode,                    KeyEvent event) {if (keycode = = Keyevent.keycode_menu && mpopupwindow.isshowing ()) {                    Mpopupwindow.dismiss ();                return true;            } return false;        }        }); Mpopupwindow = new Popupwindow (view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, True)        ; Mpopupwindow.setbackgrounddrawable(New Colordrawable (0x00000000));        SetBackgroundColor (Color.parsecolor ("#000000"));    SetCorner (R.mipmap.triangle);     }/** * Set listview Background * * @param argb color.parsecolor ("...") */public void SetBackgroundColor (int argb) {//int strokewidth = 5;//3DP Border Width int roundradius = 5;// 8DP fillet radius//int strokecolor = Color.parsecolor ("#2E3135");//Border color//int fillcolor = Color.parsecolor ("#DFDFE0"        );//Internal fill color gradientdrawable gd = new gradientdrawable ();//Create drawable Gd.setcolor (ARGB);        Gd.setcornerradius (Roundradius);//Gd.setstroke (Strokewidth, Strokecolor);    Mlistview.setbackgrounddrawable (GD); }/** * Set the bottom corner icon * * @param resId */public void SetCorner (int resId) {Cornericon.setbackgroun    Dresource (RESID); } protected View Oncreateview (context context) {return Layoutinflater.from (context). Inflate (R.layout.layout_pop    Menu_more, NULL); } protected ImageView Findcornerview (view view) {return (ImageView) View.findviewbyid (R.ID.CORNER_IV);    } protected ListView findListView (view view) {return (ListView) View.findviewbyid (R.id.menu_listview);     }/** * The adapter in the menu list.     * * @param context * @param items represents all menu items.        * @return */protected Baseadapter Oncreateadapter (context context, arraylist<popmenumoreitem> items) {    return new Popmenumoreadapter (context, items); }/** * Add menu item * * @param item */public void AddItem (Popmenumoreitem item) {Mitemlist.add (it        EM);    Madapter.notifydatasetchanged ();        public void Additems (list<popmenumoreitem> items) {if (items! = null) {mitemlist.clear ();        } for (Popmenumoreitem item:items) {mitemlist.add (item);    } madapter.notifydatasetchanged ();     }/** * is displayed as a drop-down control for the specified view. * * @param the view */public void Showasdropdo specified by the parentWN (View parent) {Mpopupwindow.showasdropdown (parent);     }/** * hides the menu.    */public void Dismiss () {Mpopupwindow.dismiss ();     }/** * Set menu selection listener.     * * @param listener listener.    */public void Setonitemselectedlistener (Onitemselectedlistener listener) {Mlistener = listener;     }/** * Whether the current menu is being displayed.    * * @return */public boolean isshowing () {return mpopupwindow.isshowing ();     }/** * menu item Select Listener Interface.         */public interface Onitemselectedlistener {/** * menu is selected when the callback interface.         * * @param view of the selected content.         * @param item is selected menu item.         * @param position the selected position.    */void selected (View view, popmenumoreitem item, int position); }}
2. The adapter of the ListView in the menu: Popmenumoreadapter

/** * @author Soban * @create 2017/4/12 10:29.    */public class Popmenumoreadapter extends Baseadapter {private arraylist<popmenumoreitem> items;    Private context context;        Public Popmenumoreadapter (context context, arraylist<popmenumoreitem> items) {This.context = context;    This.items = items;    } @Override public int getcount () {return items.size ();    } @Override public Popmenumoreitem getItem (int position) {return items.get (position);    } @Override public long getitemid (int position) {return position; } @Override public View getView (int position, view view, ViewGroup parent) {if (view = = null) {V            Iew = Layoutinflater.from (context). Inflate (R.layout.item_popmenu_more, NULL);            Viewholder holder = new Viewholder ();            Holder.icon = (ImageView) View.findviewbyid (R.id.menu_icon);            Holder.text = (TextView) View.findviewbyid (R.id.menu_text); view.seTtag (holder);        } else if (view.getparent () = null) {((ViewGroup) view.getparent ()). Removeview (view);        } Viewholder holder = (viewholder) view.gettag ();        Popmenumoreitem item = items.get (position);        if (item.getresid () = = 0) {holder.icon.setVisibility (view.gone);        } holder.text.setText (Item.gettext ());    return view;        } private class Viewholder {ImageView icon;    TextView text; }}
4. Item:popmenumoreitem in the menu item

/** * menu item. */public class Popmenumoreitem {public    int id;//Identity public    int resId;//resource icon public    String text;//Text    Pub LIC popmenumoreitem (int id, String text) {        this.id = ID;        This.resid = 0;        This.text = text;    }    public Popmenumoreitem (int id, int resId, String text) {        this.id = ID;        This.resid = resId;        This.text = text;    }    public int getId () {        return ID;    }    public void setId (int id) {        this.id = ID;    }    public int Getresid () {        return resId;    }    public void Setresid (int resId) {        this.resid = resId;    }    Public String GetText () {        return text;    }    public void SetText (String text) {        this.text = text;    }}
4. Width adaptation content, non-scrolling Listview:popmenumorelistview

/** * Width Adaptation content of the ListView. * AUTHOR:MSDX ([email protected]) * time:14-9-2 pm 5:14 */public Class Popmenumorelistview extends ListView {pub    Lic Popmenumorelistview (Context context) {super (context);    } public Popmenumorelistview (context context, AttributeSet Attrs) {Super (context, attrs); } public Popmenumorelistview (context context, AttributeSet attrs, int defstyle) {Super (context, Attrs, Defstyle    );        } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {int width = 0;            for (int i = 0; i < Getchildcount (); i++) {View child = Getchildat (i);            Child.measure (Measurespec.makemeasurespec (0, measurespec.unspecified), Heightmeasurespec);            int w = child.getmeasuredwidth ();        if (w > width) width = w; } Widthmeasurespec = Measurespec.makemeasurespec (width + getpaddingleft () + getpaddingright (), measurespec.exactly)        ; Super.onmeasure (WidthmeaSurespec, Heightmeasurespec); }}

5, the layout of the item: Item_popmenu_more.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/    Android "Android:layout_width=" Wrap_content "android:layout_height=" wrap_content "android:paddingbottom=" 10dip " android:paddingleft= "20dip" android:paddingright= "20dip" android:paddingtop= "10dip" > <imageview an Droid:id= "@+id/menu_icon" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" an        Droid:layout_gravity= "center_vertical" android:layout_marginleft= "5dip" android:layout_marginright= "5dip" android:src= "@mipmap/demand_icon_location"/> <textview android:id= "@+id/menu_text" Android:la        Yout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "center_vertical" Android:singleline= "true" android:textcolor= "#FFFFFF"/></linearlayout>
6, more menu layout: layout_popmenu_more.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/    Android "Android:layout_width=" Match_parent "android:layout_height=" wrap_content "android:orientation=" vertical " android:paddingright= "5dip" > <imageview android:id= "@+id/corner_iv" android:layout_width= "Wrap_c Ontent "android:layout_height=" wrap_content "android:layout_gravity=" right "Android:layout_marginrigh t= "15dip" android:contentdescription= "@null"/> <soban.orderscroll.popmenumorelistview android:id= " @+id/menu_listview "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android: Layout_gravity= "Right" android:cachecolorhint= "@android: Color/transparent" android:listselector= "@android: Co Lor/transparent "android:divider=" #FFFFFF "android:dividerheight=" 1px "android:focusable=" true "/> </LinearLayout>
7. Example Activity:mainactivity

public class Mainactivity extends Activity {private static final int user_search = 0;    private static final int user_add = 1;    Private Popmenumore Mmenu;    Private TextView Mtextview;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Initmenu ();        Mtextview = (TextView) Findviewbyid (R.ID.HELLO_TV);                 Mtextview.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {            Mmenu.showasdropdown (Mtextview);    }        });       private void Initmenu () {mmenu = new Popmenumore (this);       Mmenu.setcorner (r.mipmap.demand_icon_location);        Mmenu.setbackgroundcolor (Color.parsecolor ("#ff8800"));        arraylist<popmenumoreitem> items = new arraylist<> ();        Items.Add (New Popmenumoreitem (User_search, "search")); Items.Add (New Popmenumoreitem (User_adD, "add"));        Items.Add (New Popmenumoreitem (User_search, "search"));        Items.Add (New Popmenumoreitem (User_add, "add"));        Items.Add (New Popmenumoreitem (User_search, "search"));        Items.Add (New Popmenumoreitem (User_add, "add"));        /*items.add (New Popmenumoreitem (User_search, R.mipmap.demand_icon_number, "search"));        Items.Add (New Popmenumoreitem (User_add, R.mipmap.demand_icon_location, "add"));        Items.Add (New Popmenumoreitem (User_search, R.mipmap.demand_icon_number, "search"));        Items.Add (New Popmenumoreitem (User_add, R.mipmap.demand_icon_location, "add"));        Items.Add (New Popmenumoreitem (User_search, R.mipmap.demand_icon_number, "search"));        Items.Add (New Popmenumoreitem (User_add, R.mipmap.demand_icon_location, "add")); */Mmenu.additems (items); Mmenu.setonitemselectedlistener (New Popmenumore.onitemselectedlistener () {@Override public void sel ected (view view, popmenumoreitem item, int position) {switch (iteM.id) {case user_search://startactivity (The new Intent (this, usersearchactivity.cl                        ));                    Break                        Case user_add://StartActivity (New Intent (Getactivity (), useraddactivity.class));                Break    }            }        }); }}
8. Example layout: Activity_main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    xmlns:tools=" Http://schemas.android.com/tools "    android:id=" @+id/activity_main "    android: Layout_width= "Match_parent"    android:layout_height= "match_parent"    android:paddingbottom= "@dimen/ Activity_vertical_margin "    android:paddingleft=" @dimen/activity_horizontal_margin "    android:paddingright = "@dimen/activity_horizontal_margin"    android:paddingtop= "@dimen/activity_vertical_margin" >    < TextView        android:id= "@+id/hello_tv"        android:layout_width= "wrap_content"        android:layout_height= " Wrap_content "        android:text=" Hello world! "/></relativelayout>

9. Required Resource Documents:



Recently the project is also very urgent, here is a bit of a hurry, may write not so specific, I hope that friends can read


Reference: http://blog.csdn.net/maosidiaoxian/article/details/39178167

Code Set background fillet + border + Circle Radius: http://blog.csdn.net/houshunwei/article/details/17392409








Android uses Popupwindow to bring up more menus

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.