Android uses Popupwindow to implement click the toolbar Popup drop-down menu

Source: Internet
Author: User

1. Overview

This article will show you how to use Popupwindow to achieve the ability to tap the toolbar button pop-up drop-down menu at the top of the screen. First:






2. The code implementation first is the Activity_main.xml layout file:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:backg Round= "#897D13" tools:context= ".        Mainactivity "> <relativelayout android:id=" @+id/rl_topbar "android:layout_width=" Match_parent "        android:layout_height= "40dip" android:background= "#BF7F40" android:gravity= "center_vertical" > <textview android:id= "@+id/tv_left" android:layout_width= "70dip" Android:layout_heigh t= "30dip" android:layout_alignparentleft= "true" android:layout_marginleft= "10dip" Android            : background= "@drawable/btn_selector_pop" android:clickable= "true" android:gravity= "center"        Android:text= "left" android:textcolor= "@android: Color/white" android:textsize= "16sp"/> <textviEW android:id= "@+id/tv_middle" android:layout_width= "70dip" android:layout_height= "30dip" Android:layout_centerhorizontal= "true" android:background= "@drawable/btn_selector_pop" a Ndroid:clickable= "true" android:gravity= "center" android:text= "Middle" android:textcolor=            "@android: Color/white" android:textsize= "16sp"/> <textview android:id= "@+id/tv_right" Android:layout_width= "70dip" android:layout_height= "30dip" Android:layout_alignparentrigh            T= "true" android:layout_marginright= "10dip" android:background= "@drawable/btn_selector_pop" Android:clickable= "true" android:gravity= "center" android:text= "right" android:textcol Or= "@android: Color/white" android:textsize= "16sp"/> </RelativeLayout> <textview Andro Id:layout_width= "Wrap_coNtent "android:layout_height=" Wrap_content "android:layout_centerinparent=" true "android:text=" Drop-d Own menu "android:textcolor=" @android: Color/white "android:textsize=" 20SP "/></relativelayout>
Among them, Rl_topbar defines the top toolbar, which contains the left and right three TextView, click on these three controls will pop up the corresponding drop-down menu.
Next is the Mainactivity.java file:
Package Com.example.dropdownmenu;import Java.util.arraylist;import Java.util.hashmap;import java.util.List;import Java.util.map;import Android.os.bundle;import Android.app.activity;import android.graphics.drawable.ColorDrawable ; Import Android.view.menu;import Android.view.motionevent;import Android.view.view;import Android.view.viewgroup.layoutparams;import Android.widget.adapterview;import Android.widget.ListView;import Android.widget.popupwindow;import Android.widget.relativelayout;import Android.widget.simpleadapter;import Android.widget.textview;public class Mainactivity extends Activity {//toolbar private relativelayout rltopbar;// Left middle right three controls (toolbar) Private TextView tvleft;private TextView tvright;private TextView tvmiddle;//left middle right three pop-up windows private Popupwindow popleft;private Popupwindow popright;private Popupwindow popmiddle;//left middle right three layoutprivate View layoutLeft; Private View Layoutright;private View layoutmiddle;//left-right three ListView controls (Popup) Private ListView Menulistleft;private ListView MenulistrigHt;private ListView menulistmiddle;//Menu data Item private list<map<string, string>> listleft;private List<Map <string, string>> listright;private list<map<string, string>> listMiddle; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); Initparam ();} private void Initparam () {Rltopbar = (relativelayout) This.findviewbyid (r.id.rl_topbar); tvleft = (TextView) This.findviewbyid (R.id.tv_left); Tvleft.setonclicklistener (MyListener);//Initialize data item Listleft = new arraylist<map< String, String>> (), for (int i = 1; i < i++) {hashmap<string, string> maptemp = new hashmap<string, S Tring> (); Maptemp.put ("Item", "left" + i); Listleft.add (maptemp);} Tvright = (TextView) This.findviewbyid (r.id.tv_right); Tvright.setonclicklistener (MyListener);//Initialize data item Listright = New arraylist<map<string, string>> (); for (int i = 1; i <; i++) {hashmap<string, string> MapTemp = new hashmap<string, string> (), Maptemp.put ("Item", "right" + i); Listright.add (maptemp);} Tvmiddle = (TextView) This.findviewbyid (r.id.tv_middle); Tvmiddle.setonclicklistener (MyListener);// Initialize data item Listmiddle = new arraylist<map<string, string>> (); for (int i = 1; i < i++) {hashmap<string, St ring> maptemp = new hashmap<string, string> (), Maptemp.put ("Item", "Mid" + i); Listmiddle.add (maptemp);}} Private View.onclicklistener MyListener = new View.onclicklistener () {@Overridepublic void OnClick (View v) {switch (v.get Id ()) {case R.id.tv_left:if (popleft! = null && popleft.isshowing ()) {Popleft.dismiss ();} else {layoutleft = Getla Youtinflater (). Inflate (r.layout.pop_menulist, null); Menulistleft = (ListView) Layoutleft.findviewbyid ( R.id.menulist); Simpleadapter listadapter = new Simpleadapter (Mainactivity.this, Listleft, r.layout.pop_menuitem,new String[] {"Item"} , new int[] {r.id.menuitem}); Menulistleft.setadapter (listadapter);//Click the item in the ListViewThe processing Menulistleft.setonitemclicklistener (new Adapterview.onitemclicklistener () {@Overridepublic void Onitemclick ( adapterview<?> arg0,view arg1, int arg2, long arg3) {//change the top corresponding to the TextView value of string stritem = Listleft.get (arg2). Get ("ite M "); Tvleft.settext (stritem);//Hide pop-up window if (popleft! = null && popleft.isshowing ()) {Popleft.dismiss ();}}); /create Popup//window content for Layoutleft, which contains a listview//window width as tvleft popleft = new Popupwindow (Layoutleft, Tvleft.getwidth (), Layoutparams.wrap_content); Colordrawable cd = new colordrawable ( -0000);p opleft.setbackgrounddrawable (CD);p Opleft.setanimationstyle ( r.style.popupanimation);p opleft.update ();p Opleft.setinputmethodmode (popupwindow.input_method_needed); Popleft.settouchable (TRUE); Set Popupwindow to click Popleft.setoutsidetouchable (TRUE); Set Popupwindow external clickable popleft.setfocusable (true); Gets the focus//setting position of the Popupwindow (relative tvleft position) int topbarheight = Rltopbar.getbottom ();p opleft.showasdropdown (tvleft, 0, ( Topbarheight-tvleft.getheight ())/2);p opleft.settouchinterceptor (new View.ontouchlistener () {@Overridepublic Boolean onTouch (View V, motionevent event) {//If you click outside of Popupwindow, Popupwindow will also disappear if (event.getaction () = = Motionevent.action_outside) {Popleft.dismiss (); return true;} return false;}}); Break;case r.id.tv_right:if (popright! = null && popright.isshowing ()) {Popright.dismiss ();} else {layoutright = Getlayoutinflater (). Inflate (r.layout.pop_menulist, null); menulistright = (ListView) Layoutright.findviewbyid ( R.id.menulist); Simpleadapter listadapter = new Simpleadapter (Mainactivity.this, Listright, r.layout.pop_menuitem,new String[] {"Item" },new int[] {r.id.menuitem}); Menulistright.setadapter (listadapter);// Click the handle of item in ListView Menulistright.setonitemclicklistener (New Adapterview.onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> arg0,view arg1, int arg2, long arg3) {String stritem = Listright.get (arg2). Get ("ite M "); Tvright.settext (stritem); if (popright! = null && popright.isshowing ()) {Popright.dismiss();}}}); Popright = new Popupwindow (Layoutright, Tvright.getwidth (), layoutparams.wrap_content); Colordrawable cd = new colordrawable ( -0000);p opright.setbackgrounddrawable (CD);p Opright.setanimationstyle ( r.style.popupanimation);p opright.update ();p Opright.setinputmethodmode (popupwindow.input_method_needed); Popright.settouchable (TRUE); Set Popupwindow to click Popright.setoutsidetouchable (TRUE); Set Popupwindow external clickable popright.setfocusable (true); Get focus//Set position of Popupwindow int topbarheight = Rltopbar.getbottom ();p opright.showasdropdown (tvright, 0, (Topbarheight- Tvright.getheight ())/2);p Opright.settouchinterceptor (new View.ontouchlistener () {@Overridepublic Boolean OnTouch ( View V, motionevent event) {//If the Popupwindow is clicked externally, Popupwindow will disappear if (event.getaction () = = Motionevent.action_outside) {Popright.dismiss (); return true;} return false;}}); Break;case r.id.tv_middle:if (Popmiddle! = null && popmiddle.isshowing ()) {Popmiddle.dismiss ();} else { Layoutmiddle = Getlayoutinflater (). Inflate (r.layouT.pop_menulist, null); Menulistmiddle = (ListView) Layoutmiddle.findviewbyid (r.id.menulist); Simpleadapter listadapter = new Simpleadapter (Mainactivity.this, Listmiddle, r.layout.pop_menuitem,new String[] {"Item "},new int[] {r.id.menuitem}); Menulistmiddle.setadapter (listadapter);// Click the handle of item in ListView Menulistmiddle.setonitemclicklistener (New Adapterview.onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> arg0,view arg1, int arg2, long arg3) {String stritem = Listmiddle.get (arg2). Get ("it Em "); Tvmiddle.settext (stritem); if (popmiddle! = null && popmiddle.isshowing ()) {Popmiddle.dismiss ();}}); Popmiddle = new Popupwindow (Layoutmiddle, Tvmiddle.getwidth (), layoutparams.wrap_content); Colordrawable cd = new colordrawable ( -0000);p opmiddle.setbackgrounddrawable (CD);p Opmiddle.setanimationstyle ( r.style.popupanimation);p opmiddle.update ();p Opmiddle.setinputmethodmode (popupwindow.input_method_needed); Popmiddle.settouchable (TRUE); Set Popupwindow to click Popmiddle.setoutsidEtouchable (TRUE); Set Popupwindow external clickable popmiddle.setfocusable (true); Get focus//Set position of Popupwindow int topbarheight = Rltopbar.getbottom ();p opmiddle.showasdropdown (tvmiddle, 0, (topbarheight -Tvmiddle.getheight ())/2);p Opmiddle.settouchinterceptor (new View.ontouchlistener () {@Overridepublic Boolean OnTouch (View V, motionevent event) {//If the Popupwindow is clicked externally, Popupwindow will disappear if (event.getaction () = = Motionevent.action_ OUTSIDE) {Popmiddle.dismiss (); return true;} return false;}}); Break;default:break;}}; @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.activity_main, menu); return true;}}

The above code has the detailed comment, here does not do too much explanation! The principle is relatively simple, click on the toolbar TextView will pop up Popupwindow, which contains the ListView, display all menu items.
The popup menu window (popupwindow) layout file is Pop_menulist.xml, just a ListView
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "      android:layout_width=" fill_parent "    android:layout_height=" Wrap_content "    android: background= "@drawable/shape_bg_pop"    android:orientation= "vertical"    >    <listview        android: Id= "@+id/menulist"        android:layout_width= "fill_parent"        android:layout_height= "Wrap_content"        Android :d ivider= "#696969"        android:dividerheight= "1.0dip"        android:padding= "2dip"        android:scrollbars= " None ">    </ListView></LinearLayout>

The layout file corresponding to each menu item is Pop_menuitem.xml and contains only one TextView
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" wrap_content "    android:o rientation= "Horizontal"    android:background= "@drawable/bg_list_item_pop" >    <textview        android: Id= "@+id/menuitem"        android:layout_width= "fill_parent"        android:layout_height= "Wrap_content"        Android : textcolor= "@android: Color/white"        android:padding= "10dip"        android:textsize= "16SP"/></ Linearlayout>

Other property resources related to the file, not very important, we can download the project source for research! 3. Project Source
http://download.csdn.net/detail/chadeltu/8423251



Android uses Popupwindow to implement click the toolbar Popup drop-down menu

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.