Home | History | Annotate | Download | only in menu
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.internal.view.menu;
     18 
     19 import android.content.Context;
     20 import android.content.res.Resources;
     21 import android.os.Parcelable;
     22 import android.view.Gravity;
     23 import android.view.KeyEvent;
     24 import android.view.LayoutInflater;
     25 import android.view.MenuItem;
     26 import android.view.MotionEvent;
     27 import android.view.View;
     28 import android.view.View.MeasureSpec;
     29 import android.view.ViewGroup;
     30 import android.view.ViewTreeObserver;
     31 import android.widget.AdapterView;
     32 import android.widget.BaseAdapter;
     33 import android.widget.FrameLayout;
     34 import android.widget.ListAdapter;
     35 import android.widget.ListPopupWindow;
     36 import android.widget.PopupWindow;
     37 
     38 import java.util.ArrayList;
     39 
     40 /**
     41  * Presents a menu as a small, simple popup anchored to another view.
     42  * @hide
     43  */
     44 public class MenuPopupHelper implements AdapterView.OnItemClickListener, View.OnKeyListener,
     45         ViewTreeObserver.OnGlobalLayoutListener, PopupWindow.OnDismissListener,
     46         View.OnAttachStateChangeListener, MenuPresenter {
     47     private static final String TAG = "MenuPopupHelper";
     48 
     49     static final int ITEM_LAYOUT = com.android.internal.R.layout.popup_menu_item_layout;
     50 
     51     private final Context mContext;
     52     private final LayoutInflater mInflater;
     53     private final MenuBuilder mMenu;
     54     private final MenuAdapter mAdapter;
     55     private final boolean mOverflowOnly;
     56     private final int mPopupMaxWidth;
     57 
     58     private View mAnchorView;
     59     private ListPopupWindow mPopup;
     60     private ViewTreeObserver mTreeObserver;
     61     private Callback mPresenterCallback;
     62 
     63     boolean mForceShowIcon;
     64 
     65     private ViewGroup mMeasureParent;
     66 
     67     /** Whether the cached content width value is valid. */
     68     private boolean mHasContentWidth;
     69 
     70     /** Cached content width from {@link #measureContentWidth}. */
     71     private int mContentWidth;
     72 
     73     private int mDropDownGravity = Gravity.NO_GRAVITY;
     74 
     75     public MenuPopupHelper(Context context, MenuBuilder menu) {
     76         this(context, menu, null, false);
     77     }
     78 
     79     public MenuPopupHelper(Context context, MenuBuilder menu, View anchorView) {
     80         this(context, menu, anchorView, false);
     81     }
     82 
     83     public MenuPopupHelper(Context context, MenuBuilder menu,
     84             View anchorView, boolean overflowOnly) {
     85         mContext = context;
     86         mInflater = LayoutInflater.from(context);
     87         mMenu = menu;
     88         mAdapter = new MenuAdapter(mMenu);
     89         mOverflowOnly = overflowOnly;
     90 
     91         final Resources res = context.getResources();
     92         mPopupMaxWidth = Math.max(res.getDisplayMetrics().widthPixels / 2,
     93                 res.getDimensionPixelSize(com.android.internal.R.dimen.config_prefDialogWidth));
     94 
     95         mAnchorView = anchorView;
     96 
     97         menu.addMenuPresenter(this);
     98     }
     99 
    100     public void setAnchorView(View anchor) {
    101         mAnchorView = anchor;
    102     }
    103 
    104     public void setForceShowIcon(boolean forceShow) {
    105         mForceShowIcon = forceShow;
    106     }
    107 
    108     public void setGravity(int gravity) {
    109         mDropDownGravity = gravity;
    110     }
    111 
    112     public void show() {
    113         if (!tryShow()) {
    114             throw new IllegalStateException("MenuPopupHelper cannot be used without an anchor");
    115         }
    116     }
    117 
    118     public ListPopupWindow getPopup() {
    119         return mPopup;
    120     }
    121 
    122     public boolean tryShow() {
    123         mPopup = new ListPopupWindow(mContext, null, com.android.internal.R.attr.popupMenuStyle);
    124         mPopup.setOnDismissListener(this);
    125         mPopup.setOnItemClickListener(this);
    126         mPopup.setAdapter(mAdapter);
    127         mPopup.setModal(true);
    128 
    129         View anchor = mAnchorView;
    130         if (anchor != null) {
    131             final boolean addGlobalListener = mTreeObserver == null;
    132             mTreeObserver = anchor.getViewTreeObserver(); // Refresh to latest
    133             if (addGlobalListener) mTreeObserver.addOnGlobalLayoutListener(this);
    134             anchor.addOnAttachStateChangeListener(this);
    135             mPopup.setAnchorView(anchor);
    136             mPopup.setDropDownGravity(mDropDownGravity);
    137         } else {
    138             return false;
    139         }
    140 
    141         if (!mHasContentWidth) {
    142             mContentWidth = measureContentWidth();
    143             mHasContentWidth = true;
    144         }
    145 
    146         mPopup.setContentWidth(mContentWidth);
    147         mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
    148         mPopup.show();
    149         mPopup.getListView().setOnKeyListener(this);
    150         return true;
    151     }
    152 
    153     public void dismiss() {
    154         if (isShowing()) {
    155             mPopup.dismiss();
    156         }
    157     }
    158 
    159     public void onDismiss() {
    160         mPopup = null;
    161         mMenu.close();
    162         if (mTreeObserver != null) {
    163             if (!mTreeObserver.isAlive()) mTreeObserver = mAnchorView.getViewTreeObserver();
    164             mTreeObserver.removeGlobalOnLayoutListener(this);
    165             mTreeObserver = null;
    166         }
    167         mAnchorView.removeOnAttachStateChangeListener(this);
    168     }
    169 
    170     public boolean isShowing() {
    171         return mPopup != null && mPopup.isShowing();
    172     }
    173 
    174     @Override
    175     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    176         MenuAdapter adapter = mAdapter;
    177         adapter.mAdapterMenu.performItemAction(adapter.getItem(position), 0);
    178     }
    179 
    180     public boolean onKey(View v, int keyCode, KeyEvent event) {
    181         if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_MENU) {
    182             dismiss();
    183             return true;
    184         }
    185         return false;
    186     }
    187 
    188     private int measureContentWidth() {
    189         // Menus don't tend to be long, so this is more sane than it looks.
    190         int maxWidth = 0;
    191         View itemView = null;
    192         int itemType = 0;
    193 
    194         final ListAdapter adapter = mAdapter;
    195         final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    196         final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    197         final int count = adapter.getCount();
    198         for (int i = 0; i < count; i++) {
    199             final int positionType = adapter.getItemViewType(i);
    200             if (positionType != itemType) {
    201                 itemType = positionType;
    202                 itemView = null;
    203             }
    204 
    205             if (mMeasureParent == null) {
    206                 mMeasureParent = new FrameLayout(mContext);
    207             }
    208 
    209             itemView = adapter.getView(i, itemView, mMeasureParent);
    210             itemView.measure(widthMeasureSpec, heightMeasureSpec);
    211 
    212             final int itemWidth = itemView.getMeasuredWidth();
    213             if (itemWidth >= mPopupMaxWidth) {
    214                 return mPopupMaxWidth;
    215             } else if (itemWidth > maxWidth) {
    216                 maxWidth = itemWidth;
    217             }
    218         }
    219 
    220         return maxWidth;
    221     }
    222 
    223     @Override
    224     public void onGlobalLayout() {
    225         if (isShowing()) {
    226             final View anchor = mAnchorView;
    227             if (anchor == null || !anchor.isShown()) {
    228                 dismiss();
    229             } else if (isShowing()) {
    230                 // Recompute window size and position
    231                 mPopup.show();
    232             }
    233         }
    234     }
    235 
    236     @Override
    237     public void onViewAttachedToWindow(View v) {
    238     }
    239 
    240     @Override
    241     public void onViewDetachedFromWindow(View v) {
    242         if (mTreeObserver != null) {
    243             if (!mTreeObserver.isAlive()) mTreeObserver = v.getViewTreeObserver();
    244             mTreeObserver.removeGlobalOnLayoutListener(this);
    245         }
    246         v.removeOnAttachStateChangeListener(this);
    247     }
    248 
    249     @Override
    250     public void initForMenu(Context context, MenuBuilder menu) {
    251         // Don't need to do anything; we added as a presenter in the constructor.
    252     }
    253 
    254     @Override
    255     public MenuView getMenuView(ViewGroup root) {
    256         throw new UnsupportedOperationException("MenuPopupHelpers manage their own views");
    257     }
    258 
    259     @Override
    260     public void updateMenuView(boolean cleared) {
    261         mHasContentWidth = false;
    262 
    263         if (mAdapter != null) {
    264             mAdapter.notifyDataSetChanged();
    265         }
    266     }
    267 
    268     @Override
    269     public void setCallback(Callback cb) {
    270         mPresenterCallback = cb;
    271     }
    272 
    273     @Override
    274     public boolean onSubMenuSelected(SubMenuBuilder subMenu) {
    275         if (subMenu.hasVisibleItems()) {
    276             MenuPopupHelper subPopup = new MenuPopupHelper(mContext, subMenu, mAnchorView, false);
    277             subPopup.setCallback(mPresenterCallback);
    278 
    279             boolean preserveIconSpacing = false;
    280             final int count = subMenu.size();
    281             for (int i = 0; i < count; i++) {
    282                 MenuItem childItem = subMenu.getItem(i);
    283                 if (childItem.isVisible() && childItem.getIcon() != null) {
    284                     preserveIconSpacing = true;
    285                     break;
    286                 }
    287             }
    288             subPopup.setForceShowIcon(preserveIconSpacing);
    289 
    290             if (subPopup.tryShow()) {
    291                 if (mPresenterCallback != null) {
    292                     mPresenterCallback.onOpenSubMenu(subMenu);
    293                 }
    294                 return true;
    295             }
    296         }
    297         return false;
    298     }
    299 
    300     @Override
    301     public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
    302         // Only care about the (sub)menu we're presenting.
    303         if (menu != mMenu) return;
    304 
    305         dismiss();
    306         if (mPresenterCallback != null) {
    307             mPresenterCallback.onCloseMenu(menu, allMenusAreClosing);
    308         }
    309     }
    310 
    311     @Override
    312     public boolean flagActionItems() {
    313         return false;
    314     }
    315 
    316     public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) {
    317         return false;
    318     }
    319 
    320     public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) {
    321         return false;
    322     }
    323 
    324     @Override
    325     public int getId() {
    326         return 0;
    327     }
    328 
    329     @Override
    330     public Parcelable onSaveInstanceState() {
    331         return null;
    332     }
    333 
    334     @Override
    335     public void onRestoreInstanceState(Parcelable state) {
    336     }
    337 
    338     private class MenuAdapter extends BaseAdapter {
    339         private MenuBuilder mAdapterMenu;
    340         private int mExpandedIndex = -1;
    341 
    342         public MenuAdapter(MenuBuilder menu) {
    343             mAdapterMenu = menu;
    344             findExpandedIndex();
    345         }
    346 
    347         public int getCount() {
    348             ArrayList<MenuItemImpl> items = mOverflowOnly ?
    349                     mAdapterMenu.getNonActionItems() : mAdapterMenu.getVisibleItems();
    350             if (mExpandedIndex < 0) {
    351                 return items.size();
    352             }
    353             return items.size() - 1;
    354         }
    355 
    356         public MenuItemImpl getItem(int position) {
    357             ArrayList<MenuItemImpl> items = mOverflowOnly ?
    358                     mAdapterMenu.getNonActionItems() : mAdapterMenu.getVisibleItems();
    359             if (mExpandedIndex >= 0 && position >= mExpandedIndex) {
    360                 position++;
    361             }
    362             return items.get(position);
    363         }
    364 
    365         public long getItemId(int position) {
    366             // Since a menu item's ID is optional, we'll use the position as an
    367             // ID for the item in the AdapterView
    368             return position;
    369         }
    370 
    371         public View getView(int position, View convertView, ViewGroup parent) {
    372             if (convertView == null) {
    373                 convertView = mInflater.inflate(ITEM_LAYOUT, parent, false);
    374             }
    375 
    376             MenuView.ItemView itemView = (MenuView.ItemView) convertView;
    377             if (mForceShowIcon) {
    378                 ((ListMenuItemView) convertView).setForceShowIcon(true);
    379             }
    380             itemView.initialize(getItem(position), 0);
    381             return convertView;
    382         }
    383 
    384         void findExpandedIndex() {
    385             final MenuItemImpl expandedItem = mMenu.getExpandedItem();
    386             if (expandedItem != null) {
    387                 final ArrayList<MenuItemImpl> items = mMenu.getNonActionItems();
    388                 final int count = items.size();
    389                 for (int i = 0; i < count; i++) {
    390                     final MenuItemImpl item = items.get(i);
    391                     if (item == expandedItem) {
    392                         mExpandedIndex = i;
    393                         return;
    394                     }
    395                 }
    396             }
    397             mExpandedIndex = -1;
    398         }
    399 
    400         @Override
    401         public void notifyDataSetChanged() {
    402             findExpandedIndex();
    403             super.notifyDataSetChanged();
    404         }
    405     }
    406 }
    407