Android development tips-use PopupWindow to implement the pop-up menu

Source: Internet
Author: User

Android development tips-use PopupWindow to implement the pop-up menu

In this article, I will share with you a class that encapsulates PopupWindow to implement the pop-up menu and describe its implementation and use.

Because of the interface requirements, the android native pop-up menu cannot meet our needs, and the custom menu has become our only choice. In this article, I will share with you how to use PopupWindow to implement the pop-up menu.

1. pop-up menu encapsulation PopMenu

PopupWindow is a container floating on the Activity, which is usually used to display custom views. For example, if the input box AutoCompleteTextView is automatically completed, its prompt list is implemented using PopupWindow. The following abstract class PopMenu encapsulates the UI logic of the pop-up menu using PopupWindow, but does not include the setting of the interface layout.

/** Date: 14-6-13 * Project: Parking Lay-by */package cn. irains. access. v2.common; import android. content. context; import android. graphics. drawable. colorDrawable; import android. view. keyEvent; import android. view. view; import android. view. viewGroup; import android. widget. adapterView; import android. widget. arrayAdapter; import android. widget. listView; import android. widget. popupWindow; import java. util. arrayList;/*** encapsulate the pop-up menu. * Author: msdx (645079761@qq.com) * Time: 14-6-13 */public abstract class PopMenu {/*** context. */private Context mContext;/*** menu item */private ArrayList
 
  
MItemList;/*** list Adapter. */private ArrayAdapter
  
   
MAdapter;/*** select listener from the menu. */private OnItemSelectedListener mListener;/*** list. */private ListView mListView;/*** pop-up window. */private PopupWindow mPopupWindow; public PopMenu (Context context) {mContext = context; mItemList = new ArrayList
   
    
(2); View view = onCreateView (context); view. setFocusableInTouchMode (true); mAdapter = onCreateAdapter (context, mItemList); mListView = findListView (view); mListView. setAdapter (mAdapter); mListView. setOnItemClickListener (new AdapterView. onItemClickListener () {@ Override public void onItemClick (AdapterView
    Parent, View view, int position, long id) {Item item = mAdapter. 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);}/*** menu interface view. ** @ param context * @ return */protected abstract View onCreateView (Context context);/*** list in the menu interface View. ** @ param view * @ return */protected abstract ListView findListView (View view);/*** the adapter in the menu list. ** @ param context * @ param itemList indicates all menu items. * @ return */protected abstract ArrayAdapter
    
     
OnCreateAdapter (Context context, ArrayList
     
      
ItemList);/*** Add a menu item. ** @ param text the text of the menu item. * @ param id the ID of the menu item */public void addItem (String text, int id) {mItemList. add (new Item (text, id); mAdapter. notifyDataSetChanged ();}/*** Add a menu item. ** @ param resId the resource ID of the text in the menu item * @ param id the ID of the menu item. */public void addItem (int resId, int id) {addItem (mContext. getString (resId), id);}/*** is displayed as the drop-down control of the specified View. ** @ param parent the specified View */public void showAsDropDown (View parent) {mPopupWindow. showAsDropDown (parent);}/*** hide the menu. */public void dismiss () {mPopupWindow. dismiss ();}/*** select listener from the settings menu. ** @ param listener. */public void setOnItemSelectedListener (OnItemSelectedListener listener) {mListener = listener;}/*** whether the current menu is being displayed. ** @ return */public boolean isShowing () {return mPopupWindow. isShowing ();}/*** menu item. */public static class Item {public String text; public int id; public Item (String text, int id) {this. text = text; this. id = id ;}@ Override public String toString () {return text ;}}/*** select the listener interface from the menu. */public static interface OnItemSelectedListener {/*** specifies the callback interface when the menu is selected. ** @ param view: View of the selected content. * @ param item the menu item selected. * @ param position the selected position. */public void selected (View view, Item item, int position );}}
     
    
   
  
 

There are three abstract methods. The first one is onCreateView (Context context). Here we need to implement and return this view of our pop-up menu, then it can be loaded to the PopupWindow and displayed.

The second method is findListView (View view ). This is because our menu is usually a list, and then click to select a list, so here we need to return a ListView object to load our menu items.

The third method is onCreateAdapter, that is, the listview adapter.

This class also encapsulates an internal class Item:

/*** Menu item. */public static class Item {public String text; public int id; public Item (String text, int id) {this. text = text; this. id = id ;}@ Override public String toString () {return text ;}}
It is used to represent our menu items. text is the text information displayed in the menu, and id represents the ID of the menu item.

This abstract class also defines an OnItemSelectedListener interface, which is the callback interface when the menu item is clicked. For its description, see annotations. This is the most detailed class I have written so far in this blog.

2. Use of PopMenu

First, inherit from PopMenu and implement the abstract method:

/** Date: 14-9-2 * Project: Access-Control-V2 */package cn. irains. access. v2.usermanager; import android. content. context; import android. view. layoutInflater; import android. view. view; import android. widget. arrayAdapter; import android. widget. listView; import java. util. arrayList; import cn. irains. access. v2.R; import cn. irains. access. v2.common. popMenu;/*** Author: msdx (645079761@qq.com) * Time: 14-9-2 */public class UserMenu extends PopMenu {public UserMenu (Context context) {super (context) ;}@ Override protected ListView findListView (View view) {return (ListView) view. findViewById (R. id. menu_listview) ;}@ Override protected View onCreateView (Context context) {View view = LayoutInflater. from (context ). inflate (R. layout. menu_user, null); return view;} @ Override protected ArrayAdapter
 
  
OnCreateAdapter (Context context, ArrayList
  
   
Items) {return new ArrayAdapter
   
    
(Context, R. layout. item_menu_user, items );}}
   
  
 

The width of the ListView. If it is left empty, the width is filled with the parent control by default, just like the default height of the ViewPager parent control. If you want to adapt the width of the ListView to the content, you need to rewrite it. Refer to the previous article (two classes derived from ViewPager, Android development tips). The Code is as follows:

/** Date: 14-9-2 * Project: Access-Control-V2 */package cn. irains. access. v2.common; import android. content. context; import android. util. attributeSet; import android. view. view; import android. widget. listView;/*** the width of the content to adapt to the ListView. * Author: msdx (645079761@qq.com) * Time: 14-9-2 pm */public class WrapWidthListView extends ListView {public WrapWidthListView (Context context) {super (context );} public WrapWidthListView (Context context, AttributeSet attrs) {super (context, attrs);} public WrapWidthListView (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 );}}

The layout file of the pop-up menu is as follows:
 
     
      
  
 
The ImageView is a black triangle. At last, I will understand it. The ListView background is a black image.

The layout of the item is just a TextView. The Code is as follows:

 
 

The Code is as follows:
    private static final int USER_SEARCH = 0;    private static final int USER_ADD = 1;    private UserMenu mMenu;    private void initMenu() {        mMenu = new UserMenu(context);        mMenu.addItem(R.string.user_search, USER_SEARCH);        mMenu.addItem(R.string.user_add, USER_ADD);        mMenu.setOnItemSelectedListener(new PopMenu.OnItemSelectedListener() {            @Override            public void selected(View view, PopMenu.Item item, int position) {                switch (item.id) {                    case USER_SEARCH:                        startActivity(new Intent(getActivity(), UserSearchActivity.class));                        break;                    case USER_ADD:                        startActivity(new Intent(getActivity(), UserAddActivity.class));                        break;                }            }        });    }
Initialize the menu code in onCreate or fragment of the activity, and call mMenu. showAsDropDown (view) when you need to display it. It is displayed as the view drop-down menu. The effect is as follows:


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.