MenuPopupHelper.java revision f0ad6e6eaf48ac8f4007232ad0a8511a7b5cfc0e
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 setAnchorView(View anchor) {
72        mAnchorView = new WeakReference<View>(anchor);
73    }
74
75    public void show() {
76        if (!tryShow()) {
77            throw new IllegalStateException("MenuPopupHelper cannot be used without an anchor");
78        }
79    }
80
81    public boolean tryShow() {
82        mPopup = new ListPopupWindow(mContext, null, com.android.internal.R.attr.popupMenuStyle);
83        mPopup.setOnItemClickListener(this);
84        mPopup.setOnDismissListener(this);
85
86        final MenuAdapter adapter = mOverflowOnly ?
87                mMenu.getOverflowMenuAdapter(MenuBuilder.TYPE_POPUP) :
88                mMenu.getMenuAdapter(MenuBuilder.TYPE_POPUP);
89        mPopup.setAdapter(adapter);
90        mPopup.setModal(true);
91
92        View anchor = mAnchorView != null ? mAnchorView.get() : null;
93        if (anchor == null && mMenu instanceof SubMenuBuilder) {
94            SubMenuBuilder subMenu = (SubMenuBuilder) mMenu;
95            final MenuItemImpl itemImpl = (MenuItemImpl) subMenu.getItem();
96            anchor = itemImpl.getItemView(MenuBuilder.TYPE_ACTION_BUTTON, null);
97            mAnchorView = new WeakReference<View>(anchor);
98        }
99
100        if (anchor != null) {
101            mTreeObserver = anchor.getViewTreeObserver();
102            mTreeObserver.addOnGlobalLayoutListener(this);
103            mPopup.setAnchorView(anchor);
104        } else {
105            return false;
106        }
107
108        mPopup.setContentWidth(Math.min(measureContentWidth(adapter), mPopupMaxWidth));
109        mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
110        mPopup.show();
111        mPopup.getListView().setOnKeyListener(this);
112        return true;
113    }
114
115    public void dismiss() {
116        if (isShowing()) {
117            mPopup.dismiss();
118        }
119    }
120
121    public void onDismiss() {
122        mPopup = null;
123        if (mTreeObserver != null) {
124            mTreeObserver.removeGlobalOnLayoutListener(MenuPopupHelper.this);
125            mTreeObserver = null;
126        }
127    }
128
129    public boolean isShowing() {
130        return mPopup != null && mPopup.isShowing();
131    }
132
133    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
134        MenuItem item = null;
135        if (mOverflowOnly) {
136            item = mMenu.getOverflowItem(position);
137        } else {
138            item = mMenu.getVisibleItems().get(position);
139        }
140        mMenu.performItemAction(item, 0);
141        dismiss();
142    }
143
144    public boolean onKey(View v, int keyCode, KeyEvent event) {
145        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_MENU) {
146            dismiss();
147            return true;
148        }
149        return false;
150    }
151
152    private int measureContentWidth(MenuAdapter adapter) {
153        // Menus don't tend to be long, so this is more sane than it looks.
154        int width = 0;
155        View itemView = null;
156        int itemType = 0;
157        final int widthMeasureSpec =
158            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
159        final int heightMeasureSpec =
160            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
161        final int count = adapter.getCount();
162        for (int i = 0; i < count; i++) {
163            final int positionType = adapter.getItemViewType(i);
164            if (positionType != itemType) {
165                itemType = positionType;
166                itemView = null;
167            }
168            itemView = adapter.getView(i, itemView, null);
169            itemView.measure(widthMeasureSpec, heightMeasureSpec);
170            width = Math.max(width, itemView.getMeasuredWidth());
171        }
172        return width;
173    }
174
175    @Override
176    public void onGlobalLayout() {
177        if (!isShowing()) {
178            mTreeObserver.removeGlobalOnLayoutListener(this);
179            mTreeObserver = null;
180        } else {
181            final View anchor = mAnchorView != null ? mAnchorView.get() : null;
182            if (anchor != null && !anchor.isShown()) {
183                dismiss();
184            } else {
185                // Recompute window size and position
186                mPopup.show();
187            }
188        }
189    }
190}
191