MenuPopupHelper.java revision 5e3f284baa271cb0fbf90e504d19fdd2e385382e
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
17package com.android.internal.view.menu;
18
19import com.android.internal.view.menu.MenuBuilder.MenuAdapter;
20
21import android.content.Context;
22import android.util.DisplayMetrics;
23import android.view.KeyEvent;
24import android.view.MenuItem;
25import android.view.View;
26import android.view.View.MeasureSpec;
27import android.view.ViewTreeObserver;
28import android.widget.AdapterView;
29import android.widget.ListPopupWindow;
30import android.widget.PopupWindow;
31
32import java.lang.ref.WeakReference;
33
34/**
35 * @hide
36 */
37public class MenuPopupHelper implements AdapterView.OnItemClickListener, View.OnKeyListener,
38        ViewTreeObserver.OnGlobalLayoutListener, PopupWindow.OnDismissListener {
39    private static final String TAG = "MenuPopupHelper";
40
41    private Context mContext;
42    private ListPopupWindow mPopup;
43    private MenuBuilder mMenu;
44    private int mPopupMaxWidth;
45    private WeakReference<View> mAnchorView;
46    private boolean mOverflowOnly;
47    private ViewTreeObserver mTreeObserver;
48
49    public MenuPopupHelper(Context context, MenuBuilder menu) {
50        this(context, menu, null, false);
51    }
52
53    public MenuPopupHelper(Context context, MenuBuilder menu, View anchorView) {
54        this(context, menu, anchorView, false);
55    }
56
57    public MenuPopupHelper(Context context, MenuBuilder menu,
58            View anchorView, boolean overflowOnly) {
59        mContext = context;
60        mMenu = menu;
61        mOverflowOnly = overflowOnly;
62
63        final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
64        mPopupMaxWidth = metrics.widthPixels / 2;
65
66        if (anchorView != null) {
67            mAnchorView = new WeakReference<View>(anchorView);
68        }
69    }
70
71    public void show() {
72        if (!tryShow()) {
73            throw new IllegalStateException("MenuPopupHelper cannot be used without an anchor");
74        }
75    }
76
77    public boolean tryShow() {
78        mPopup = new ListPopupWindow(mContext, null, com.android.internal.R.attr.popupMenuStyle);
79        mPopup.setOnItemClickListener(this);
80        mPopup.setOnDismissListener(this);
81
82        final MenuAdapter adapter = mOverflowOnly ?
83                mMenu.getOverflowMenuAdapter(MenuBuilder.TYPE_POPUP) :
84                mMenu.getMenuAdapter(MenuBuilder.TYPE_POPUP);
85        mPopup.setAdapter(adapter);
86        mPopup.setModal(true);
87
88        View anchor = mAnchorView != null ? mAnchorView.get() : null;
89        if (anchor == null && mMenu instanceof SubMenuBuilder) {
90            SubMenuBuilder subMenu = (SubMenuBuilder) mMenu;
91            final MenuItemImpl itemImpl = (MenuItemImpl) subMenu.getItem();
92            anchor = itemImpl.getItemView(MenuBuilder.TYPE_ACTION_BUTTON, null);
93            mAnchorView = new WeakReference<View>(anchor);
94        }
95
96        if (anchor != null) {
97            mTreeObserver = anchor.getViewTreeObserver();
98            mTreeObserver.addOnGlobalLayoutListener(this);
99            mPopup.setAnchorView(anchor);
100        } else {
101            return false;
102        }
103
104        mPopup.setContentWidth(Math.min(measureContentWidth(adapter), mPopupMaxWidth));
105        mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
106        mPopup.show();
107        mPopup.getListView().setOnKeyListener(this);
108        return true;
109    }
110
111    public void dismiss() {
112        if (isShowing()) {
113            mPopup.dismiss();
114        }
115    }
116
117    public void onDismiss() {
118        mPopup = null;
119        if (mTreeObserver != null) {
120            mTreeObserver.removeGlobalOnLayoutListener(MenuPopupHelper.this);
121            mTreeObserver = null;
122        }
123    }
124
125    public boolean isShowing() {
126        return mPopup != null && mPopup.isShowing();
127    }
128
129    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
130        MenuItem item = null;
131        if (mOverflowOnly) {
132            item = mMenu.getOverflowItem(position);
133        } else {
134            item = mMenu.getVisibleItems().get(position);
135        }
136        mMenu.performItemAction(item, 0);
137        dismiss();
138    }
139
140    public boolean onKey(View v, int keyCode, KeyEvent event) {
141        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_MENU) {
142            dismiss();
143            return true;
144        }
145        return false;
146    }
147
148    private int measureContentWidth(MenuAdapter adapter) {
149        // Menus don't tend to be long, so this is more sane than it looks.
150        int width = 0;
151        View itemView = null;
152        int itemType = 0;
153        final int widthMeasureSpec =
154            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
155        final int heightMeasureSpec =
156            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
157        final int count = adapter.getCount();
158        for (int i = 0; i < count; i++) {
159            final int positionType = adapter.getItemViewType(i);
160            if (positionType != itemType) {
161                itemType = positionType;
162                itemView = null;
163            }
164            itemView = adapter.getView(i, itemView, null);
165            itemView.measure(widthMeasureSpec, heightMeasureSpec);
166            width = Math.max(width, itemView.getMeasuredWidth());
167        }
168        return width;
169    }
170
171    @Override
172    public void onGlobalLayout() {
173        if (!isShowing()) {
174            mTreeObserver.removeGlobalOnLayoutListener(this);
175            mTreeObserver = null;
176        } else {
177            final View anchor = mAnchorView != null ? mAnchorView.get() : null;
178            if (anchor != null && !anchor.isShown()) {
179                dismiss();
180            } else {
181                // Recompute window size and position
182                mPopup.show();
183            }
184        }
185    }
186}
187