blob: b53459e072d4ec38e25697f0b4cd74b3a64e3b08 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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
19
Alan Viverette28a84682016-01-04 13:43:23 -050020import android.annotation.NonNull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.ComponentName;
22import android.content.Context;
23import android.content.Intent;
24import android.content.pm.PackageManager;
25import android.content.pm.ResolveInfo;
26import android.content.res.Configuration;
27import android.content.res.Resources;
28import android.graphics.drawable.Drawable;
Adam Powell11ed1d62011-07-11 21:19:59 -070029import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.os.Parcelable;
31import android.util.SparseArray;
Adam Powell961dd112011-07-12 14:25:23 -070032import android.view.ActionProvider;
Adam Powell36fced92011-01-16 15:48:07 -080033import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.view.KeyCharacterMap;
35import android.view.KeyEvent;
36import android.view.Menu;
37import android.view.MenuItem;
38import android.view.SubMenu;
39import android.view.View;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040
41import java.lang.ref.WeakReference;
42import java.util.ArrayList;
43import java.util.List;
Adam Powell696cba52011-03-29 10:38:16 -070044import java.util.concurrent.CopyOnWriteArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045
46/**
47 * Implementation of the {@link android.view.Menu} interface for creating a
48 * standard menu UI.
49 */
50public class MenuBuilder implements Menu {
Adam Powell89b09da2011-07-27 11:55:29 -070051 private static final String TAG = "MenuBuilder";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
Adam Powell11ed1d62011-07-11 21:19:59 -070053 private static final String PRESENTER_KEY = "android:menu:presenters";
Adam Powell038f1c82011-07-21 14:28:10 -070054 private static final String ACTION_VIEW_STATES_KEY = "android:menu:actionviewstates";
55 private static final String EXPANDED_ACTION_VIEW_ID = "android:menu:expandedactionview";
Adam Powell11ed1d62011-07-11 21:19:59 -070056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057 private static final int[] sCategoryToOrder = new int[] {
58 1, /* No category */
59 4, /* CONTAINER */
60 5, /* SYSTEM */
61 3, /* SECONDARY */
62 2, /* ALTERNATIVE */
63 0, /* SELECTED_ALTERNATIVE */
64 };
65
66 private final Context mContext;
67 private final Resources mResources;
68
69 /**
70 * Whether the shortcuts should be qwerty-accessible. Use isQwertyMode()
71 * instead of accessing this directly.
72 */
73 private boolean mQwertyMode;
74
75 /**
76 * Whether the shortcuts should be visible on menus. Use isShortcutsVisible()
77 * instead of accessing this directly.
78 */
79 private boolean mShortcutsVisible;
80
81 /**
82 * Callback that will receive the various menu-related events generated by
83 * this class. Use getCallback to get a reference to the callback.
84 */
85 private Callback mCallback;
86
87 /** Contains all of the items for this menu */
88 private ArrayList<MenuItemImpl> mItems;
89
90 /** Contains only the items that are currently visible. This will be created/refreshed from
91 * {@link #getVisibleItems()} */
92 private ArrayList<MenuItemImpl> mVisibleItems;
93 /**
94 * Whether or not the items (or any one item's shown state) has changed since it was last
95 * fetched from {@link #getVisibleItems()}
96 */
97 private boolean mIsVisibleItemsStale;
Adam Powell96675b12010-06-10 18:58:59 -070098
99 /**
100 * Contains only the items that should appear in the Action Bar, if present.
101 */
102 private ArrayList<MenuItemImpl> mActionItems;
103 /**
104 * Contains items that should NOT appear in the Action Bar, if present.
105 */
106 private ArrayList<MenuItemImpl> mNonActionItems;
Adam Powell696cba52011-03-29 10:38:16 -0700107
Adam Powell36fced92011-01-16 15:48:07 -0800108 /**
Adam Powell96675b12010-06-10 18:58:59 -0700109 * Whether or not the items (or any one item's action state) has changed since it was
110 * last fetched.
111 */
112 private boolean mIsActionItemsStale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
114 /**
Adam Powell4d9861e2010-08-17 11:14:40 -0700115 * Default value for how added items should show in the action list.
116 */
117 private int mDefaultShowAsAction = MenuItem.SHOW_AS_ACTION_NEVER;
118
119 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 * Current use case is Context Menus: As Views populate the context menu, each one has
121 * extra information that should be passed along. This is the current menu info that
122 * should be set on all items added to this menu.
123 */
124 private ContextMenuInfo mCurrentMenuInfo;
125
126 /** Header title for menu types that have a header (context and submenus) */
127 CharSequence mHeaderTitle;
128 /** Header icon for menu types that have a header and support icons (context) */
129 Drawable mHeaderIcon;
130 /** Header custom view for menu types that have a header and support custom views (context) */
131 View mHeaderView;
132
133 /**
134 * Contains the state of the View hierarchy for all menu views when the menu
135 * was frozen.
136 */
137 private SparseArray<Parcelable> mFrozenViewStates;
138
139 /**
140 * Prevents onItemsChanged from doing its junk, useful for batching commands
141 * that may individually call onItemsChanged.
142 */
143 private boolean mPreventDispatchingItemsChanged = false;
Adam Powell696cba52011-03-29 10:38:16 -0700144 private boolean mItemsChangedWhileDispatchPrevented = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146 private boolean mOptionalIconsVisible = false;
Adam Powell2fbf4de62010-09-30 15:46:46 -0700147
Adam Powell696cba52011-03-29 10:38:16 -0700148 private boolean mIsClosing = false;
Adam Powell36fced92011-01-16 15:48:07 -0800149
Adam Powell696cba52011-03-29 10:38:16 -0700150 private ArrayList<MenuItemImpl> mTempShortcutItemList = new ArrayList<MenuItemImpl>();
Adam Powell1821ff92011-01-24 21:44:28 -0800151
Adam Powell696cba52011-03-29 10:38:16 -0700152 private CopyOnWriteArrayList<WeakReference<MenuPresenter>> mPresenters =
153 new CopyOnWriteArrayList<WeakReference<MenuPresenter>>();
Adam Powell6b0e97c2011-08-03 12:06:32 -0700154
155 /**
156 * Currently expanded menu item; must be collapsed when we clear.
157 */
158 private MenuItemImpl mExpandedItem;
Tarun Lohani0b842b42017-07-26 11:57:05 -0700159
160 /**
161 * Whether group dividers are enabled.
162 */
163 private boolean mGroupDividerEnabled = false;
164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 /**
Adam Powell696cba52011-03-29 10:38:16 -0700166 * Called by menu to notify of close and selection changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 */
168 public interface Callback {
169 /**
170 * Called when a menu item is selected.
171 * @param menu The menu that is the parent of the item
172 * @param item The menu item that is selected
173 * @return whether the menu item selection was handled
174 */
175 public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item);
176
177 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 * Called when the mode of the menu changes (for example, from icon to expanded).
179 *
180 * @param menu the menu that has changed modes
181 */
182 public void onMenuModeChange(MenuBuilder menu);
183 }
184
185 /**
186 * Called by menu items to execute their associated action
187 */
188 public interface ItemInvoker {
189 public boolean invokeItem(MenuItemImpl item);
190 }
191
192 public MenuBuilder(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 mContext = context;
194 mResources = context.getResources();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 mItems = new ArrayList<MenuItemImpl>();
196
197 mVisibleItems = new ArrayList<MenuItemImpl>();
198 mIsVisibleItemsStale = true;
199
Adam Powell96675b12010-06-10 18:58:59 -0700200 mActionItems = new ArrayList<MenuItemImpl>();
201 mNonActionItems = new ArrayList<MenuItemImpl>();
202 mIsActionItemsStale = true;
203
Jeff Brown4aed78b2011-01-14 17:36:55 -0800204 setShortcutsVisibleInner(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 }
206
Adam Powell4d9861e2010-08-17 11:14:40 -0700207 public MenuBuilder setDefaultShowAsAction(int defaultShowAsAction) {
208 mDefaultShowAsAction = defaultShowAsAction;
209 return this;
210 }
Adam Powell696cba52011-03-29 10:38:16 -0700211
212 /**
213 * Add a presenter to this menu. This will only hold a WeakReference;
214 * you do not need to explicitly remove a presenter, but you can using
215 * {@link #removeMenuPresenter(MenuPresenter)}.
216 *
217 * @param presenter The presenter to add
218 */
219 public void addMenuPresenter(MenuPresenter presenter) {
Alan Viverette3d0f21d2014-07-10 16:15:01 -0700220 addMenuPresenter(presenter, mContext);
221 }
222
223 /**
224 * Add a presenter to this menu that uses an alternate context for
225 * inflating menu items. This will only hold a WeakReference; you do not
226 * need to explicitly remove a presenter, but you can using
227 * {@link #removeMenuPresenter(MenuPresenter)}.
228 *
229 * @param presenter The presenter to add
230 * @param menuContext The context used to inflate menu items
231 */
232 public void addMenuPresenter(MenuPresenter presenter, Context menuContext) {
Adam Powell696cba52011-03-29 10:38:16 -0700233 mPresenters.add(new WeakReference<MenuPresenter>(presenter));
Alan Viverette3d0f21d2014-07-10 16:15:01 -0700234 presenter.initForMenu(menuContext, this);
Adam Powell696cba52011-03-29 10:38:16 -0700235 mIsActionItemsStale = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 }
237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 /**
Adam Powell696cba52011-03-29 10:38:16 -0700239 * Remove a presenter from this menu. That presenter will no longer
240 * receive notifications of updates to this menu's data.
241 *
242 * @param presenter The presenter to remove
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 */
Adam Powell696cba52011-03-29 10:38:16 -0700244 public void removeMenuPresenter(MenuPresenter presenter) {
245 for (WeakReference<MenuPresenter> ref : mPresenters) {
246 final MenuPresenter item = ref.get();
247 if (item == null || item == presenter) {
248 mPresenters.remove(ref);
249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 }
252
Adam Powell696cba52011-03-29 10:38:16 -0700253 private void dispatchPresenterUpdate(boolean cleared) {
254 if (mPresenters.isEmpty()) return;
255
Adam Powell640a66e2011-04-29 10:18:53 -0700256 stopDispatchingItemsChanged();
Adam Powell696cba52011-03-29 10:38:16 -0700257 for (WeakReference<MenuPresenter> ref : mPresenters) {
258 final MenuPresenter presenter = ref.get();
259 if (presenter == null) {
260 mPresenters.remove(ref);
261 } else {
262 presenter.updateMenuView(cleared);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 }
264 }
Adam Powell640a66e2011-04-29 10:18:53 -0700265 startDispatchingItemsChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 }
267
Adam Powellc0cc6802013-12-03 18:58:29 -0800268 private boolean dispatchSubMenuSelected(SubMenuBuilder subMenu,
269 MenuPresenter preferredPresenter) {
Adam Powell696cba52011-03-29 10:38:16 -0700270 if (mPresenters.isEmpty()) return false;
271
272 boolean result = false;
273
Adam Powellc0cc6802013-12-03 18:58:29 -0800274 // Try the preferred presenter first.
275 if (preferredPresenter != null) {
276 result = preferredPresenter.onSubMenuSelected(subMenu);
277 }
278
Adam Powell696cba52011-03-29 10:38:16 -0700279 for (WeakReference<MenuPresenter> ref : mPresenters) {
280 final MenuPresenter presenter = ref.get();
281 if (presenter == null) {
282 mPresenters.remove(ref);
283 } else if (!result) {
284 result = presenter.onSubMenuSelected(subMenu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 }
286 }
Adam Powell696cba52011-03-29 10:38:16 -0700287 return result;
288 }
289
Adam Powell11ed1d62011-07-11 21:19:59 -0700290 private void dispatchSaveInstanceState(Bundle outState) {
291 if (mPresenters.isEmpty()) return;
292
293 SparseArray<Parcelable> presenterStates = new SparseArray<Parcelable>();
294
295 for (WeakReference<MenuPresenter> ref : mPresenters) {
296 final MenuPresenter presenter = ref.get();
297 if (presenter == null) {
298 mPresenters.remove(ref);
299 } else {
300 final int id = presenter.getId();
301 if (id > 0) {
302 final Parcelable state = presenter.onSaveInstanceState();
303 if (state != null) {
304 presenterStates.put(id, state);
305 }
306 }
307 }
308 }
309
310 outState.putSparseParcelableArray(PRESENTER_KEY, presenterStates);
311 }
312
313 private void dispatchRestoreInstanceState(Bundle state) {
314 SparseArray<Parcelable> presenterStates = state.getSparseParcelableArray(PRESENTER_KEY);
315
316 if (presenterStates == null || mPresenters.isEmpty()) return;
317
318 for (WeakReference<MenuPresenter> ref : mPresenters) {
319 final MenuPresenter presenter = ref.get();
320 if (presenter == null) {
321 mPresenters.remove(ref);
322 } else {
323 final int id = presenter.getId();
324 if (id > 0) {
325 Parcelable parcel = presenterStates.get(id);
326 if (parcel != null) {
327 presenter.onRestoreInstanceState(parcel);
328 }
329 }
330 }
331 }
332 }
333
334 public void savePresenterStates(Bundle outState) {
335 dispatchSaveInstanceState(outState);
336 }
337
338 public void restorePresenterStates(Bundle state) {
339 dispatchRestoreInstanceState(state);
340 }
341
Adam Powell038f1c82011-07-21 14:28:10 -0700342 public void saveActionViewStates(Bundle outStates) {
343 SparseArray<Parcelable> viewStates = null;
344
345 final int itemCount = size();
346 for (int i = 0; i < itemCount; i++) {
347 final MenuItem item = getItem(i);
348 final View v = item.getActionView();
349 if (v != null && v.getId() != View.NO_ID) {
350 if (viewStates == null) {
351 viewStates = new SparseArray<Parcelable>();
352 }
353 v.saveHierarchyState(viewStates);
354 if (item.isActionViewExpanded()) {
355 outStates.putInt(EXPANDED_ACTION_VIEW_ID, item.getItemId());
356 }
357 }
358 if (item.hasSubMenu()) {
359 final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();
360 subMenu.saveActionViewStates(outStates);
361 }
362 }
363
364 if (viewStates != null) {
365 outStates.putSparseParcelableArray(getActionViewStatesKey(), viewStates);
366 }
367 }
368
369 public void restoreActionViewStates(Bundle states) {
370 if (states == null) {
371 return;
372 }
373
374 SparseArray<Parcelable> viewStates = states.getSparseParcelableArray(
375 getActionViewStatesKey());
376
377 final int itemCount = size();
378 for (int i = 0; i < itemCount; i++) {
379 final MenuItem item = getItem(i);
380 final View v = item.getActionView();
381 if (v != null && v.getId() != View.NO_ID) {
382 v.restoreHierarchyState(viewStates);
383 }
384 if (item.hasSubMenu()) {
385 final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();
386 subMenu.restoreActionViewStates(states);
387 }
388 }
389
390 final int expandedId = states.getInt(EXPANDED_ACTION_VIEW_ID);
391 if (expandedId > 0) {
392 MenuItem itemToExpand = findItem(expandedId);
393 if (itemToExpand != null) {
394 itemToExpand.expandActionView();
395 }
396 }
397 }
398
399 protected String getActionViewStatesKey() {
400 return ACTION_VIEW_STATES_KEY;
401 }
402
Adam Powell696cba52011-03-29 10:38:16 -0700403 public void setCallback(Callback cb) {
404 mCallback = cb;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 }
406
407 /**
408 * Adds an item to the menu. The other add methods funnel to this.
409 */
410 private MenuItem addInternal(int group, int id, int categoryOrder, CharSequence title) {
411 final int ordering = getOrdering(categoryOrder);
412
Deepanshu Gupta10019612014-04-18 12:32:38 -0700413 final MenuItemImpl item = createNewMenuItem(group, id, categoryOrder, ordering, title,
414 mDefaultShowAsAction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415
416 if (mCurrentMenuInfo != null) {
417 // Pass along the current menu info
418 item.setMenuInfo(mCurrentMenuInfo);
419 }
420
421 mItems.add(findInsertIndex(mItems, ordering), item);
Adam Powell696cba52011-03-29 10:38:16 -0700422 onItemsChanged(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423
424 return item;
425 }
Deepanshu Gupta10019612014-04-18 12:32:38 -0700426
427 // Layoutlib overrides this method to return its custom implementation of MenuItemImpl
428 private MenuItemImpl createNewMenuItem(int group, int id, int categoryOrder, int ordering,
429 CharSequence title, int defaultShowAsAction) {
430 return new MenuItemImpl(this, group, id, categoryOrder, ordering, title,
431 defaultShowAsAction);
432 }
433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 public MenuItem add(CharSequence title) {
435 return addInternal(0, 0, 0, title);
436 }
437
438 public MenuItem add(int titleRes) {
439 return addInternal(0, 0, 0, mResources.getString(titleRes));
440 }
441
442 public MenuItem add(int group, int id, int categoryOrder, CharSequence title) {
443 return addInternal(group, id, categoryOrder, title);
444 }
445
446 public MenuItem add(int group, int id, int categoryOrder, int title) {
447 return addInternal(group, id, categoryOrder, mResources.getString(title));
448 }
449
450 public SubMenu addSubMenu(CharSequence title) {
451 return addSubMenu(0, 0, 0, title);
452 }
453
454 public SubMenu addSubMenu(int titleRes) {
455 return addSubMenu(0, 0, 0, mResources.getString(titleRes));
456 }
457
458 public SubMenu addSubMenu(int group, int id, int categoryOrder, CharSequence title) {
459 final MenuItemImpl item = (MenuItemImpl) addInternal(group, id, categoryOrder, title);
460 final SubMenuBuilder subMenu = new SubMenuBuilder(mContext, this, item);
461 item.setSubMenu(subMenu);
462
463 return subMenu;
464 }
465
466 public SubMenu addSubMenu(int group, int id, int categoryOrder, int title) {
467 return addSubMenu(group, id, categoryOrder, mResources.getString(title));
468 }
469
Tarun Lohani0b842b42017-07-26 11:57:05 -0700470 @Override
471 public void setGroupDividerEnabled(boolean groupDividerEnabled) {
472 mGroupDividerEnabled = groupDividerEnabled;
473 }
474
475 public boolean isGroupDividerEnabled() {
476 return mGroupDividerEnabled;
477 }
478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 public int addIntentOptions(int group, int id, int categoryOrder, ComponentName caller,
480 Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
481 PackageManager pm = mContext.getPackageManager();
482 final List<ResolveInfo> lri =
483 pm.queryIntentActivityOptions(caller, specifics, intent, 0);
484 final int N = lri != null ? lri.size() : 0;
485
486 if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
487 removeGroup(group);
488 }
489
490 for (int i=0; i<N; i++) {
491 final ResolveInfo ri = lri.get(i);
492 Intent rintent = new Intent(
493 ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
494 rintent.setComponent(new ComponentName(
495 ri.activityInfo.applicationInfo.packageName,
496 ri.activityInfo.name));
497 final MenuItem item = add(group, id, categoryOrder, ri.loadLabel(pm))
498 .setIcon(ri.loadIcon(pm))
499 .setIntent(rintent);
500 if (outSpecificItems != null && ri.specificIndex >= 0) {
501 outSpecificItems[ri.specificIndex] = item;
502 }
503 }
504
505 return N;
506 }
507
508 public void removeItem(int id) {
509 removeItemAtInt(findItemIndex(id), true);
510 }
511
512 public void removeGroup(int group) {
513 final int i = findGroupIndex(group);
514
515 if (i >= 0) {
516 final int maxRemovable = mItems.size() - i;
517 int numRemoved = 0;
518 while ((numRemoved++ < maxRemovable) && (mItems.get(i).getGroupId() == group)) {
519 // Don't force update for each one, this method will do it at the end
520 removeItemAtInt(i, false);
521 }
522
523 // Notify menu views
Adam Powell696cba52011-03-29 10:38:16 -0700524 onItemsChanged(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 }
526 }
527
528 /**
529 * Remove the item at the given index and optionally forces menu views to
530 * update.
531 *
532 * @param index The index of the item to be removed. If this index is
533 * invalid an exception is thrown.
534 * @param updateChildrenOnMenuViews Whether to force update on menu views.
535 * Please make sure you eventually call this after your batch of
536 * removals.
537 */
538 private void removeItemAtInt(int index, boolean updateChildrenOnMenuViews) {
539 if ((index < 0) || (index >= mItems.size())) return;
540
541 mItems.remove(index);
542
Adam Powell696cba52011-03-29 10:38:16 -0700543 if (updateChildrenOnMenuViews) onItemsChanged(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 }
545
546 public void removeItemAt(int index) {
547 removeItemAtInt(index, true);
548 }
549
550 public void clearAll() {
551 mPreventDispatchingItemsChanged = true;
552 clear();
553 clearHeader();
554 mPreventDispatchingItemsChanged = false;
Adam Powell696cba52011-03-29 10:38:16 -0700555 mItemsChangedWhileDispatchPrevented = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 onItemsChanged(true);
557 }
558
559 public void clear() {
Adam Powell6b0e97c2011-08-03 12:06:32 -0700560 if (mExpandedItem != null) {
561 collapseItemActionView(mExpandedItem);
562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 mItems.clear();
564
565 onItemsChanged(true);
566 }
567
568 void setExclusiveItemChecked(MenuItem item) {
569 final int group = item.getGroupId();
570
571 final int N = mItems.size();
572 for (int i = 0; i < N; i++) {
573 MenuItemImpl curItem = mItems.get(i);
574 if (curItem.getGroupId() == group) {
575 if (!curItem.isExclusiveCheckable()) continue;
576 if (!curItem.isCheckable()) continue;
577
578 // Check the item meant to be checked, uncheck the others (that are in the group)
579 curItem.setCheckedInt(curItem == item);
580 }
581 }
582 }
583
584 public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
585 final int N = mItems.size();
586
587 for (int i = 0; i < N; i++) {
588 MenuItemImpl item = mItems.get(i);
589 if (item.getGroupId() == group) {
590 item.setExclusiveCheckable(exclusive);
591 item.setCheckable(checkable);
592 }
593 }
594 }
595
596 public void setGroupVisible(int group, boolean visible) {
597 final int N = mItems.size();
598
599 // We handle the notification of items being changed ourselves, so we use setVisibleInt rather
600 // than setVisible and at the end notify of items being changed
601
602 boolean changedAtLeastOneItem = false;
603 for (int i = 0; i < N; i++) {
604 MenuItemImpl item = mItems.get(i);
605 if (item.getGroupId() == group) {
606 if (item.setVisibleInt(visible)) changedAtLeastOneItem = true;
607 }
608 }
609
Adam Powell23f4cc02011-08-18 10:30:46 -0700610 if (changedAtLeastOneItem) onItemsChanged(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 }
612
613 public void setGroupEnabled(int group, boolean enabled) {
614 final int N = mItems.size();
615
616 for (int i = 0; i < N; i++) {
617 MenuItemImpl item = mItems.get(i);
618 if (item.getGroupId() == group) {
619 item.setEnabled(enabled);
620 }
621 }
622 }
623
624 public boolean hasVisibleItems() {
625 final int size = size();
626
627 for (int i = 0; i < size; i++) {
628 MenuItemImpl item = mItems.get(i);
629 if (item.isVisible()) {
630 return true;
631 }
632 }
633
634 return false;
635 }
636
637 public MenuItem findItem(int id) {
638 final int size = size();
639 for (int i = 0; i < size; i++) {
640 MenuItemImpl item = mItems.get(i);
641 if (item.getItemId() == id) {
642 return item;
643 } else if (item.hasSubMenu()) {
644 MenuItem possibleItem = item.getSubMenu().findItem(id);
645
646 if (possibleItem != null) {
647 return possibleItem;
648 }
649 }
650 }
651
652 return null;
653 }
654
655 public int findItemIndex(int id) {
656 final int size = size();
657
658 for (int i = 0; i < size; i++) {
659 MenuItemImpl item = mItems.get(i);
660 if (item.getItemId() == id) {
661 return i;
662 }
663 }
664
665 return -1;
666 }
667
668 public int findGroupIndex(int group) {
669 return findGroupIndex(group, 0);
670 }
671
672 public int findGroupIndex(int group, int start) {
673 final int size = size();
674
675 if (start < 0) {
676 start = 0;
677 }
678
679 for (int i = start; i < size; i++) {
680 final MenuItemImpl item = mItems.get(i);
681
682 if (item.getGroupId() == group) {
683 return i;
684 }
685 }
686
687 return -1;
688 }
689
690 public int size() {
691 return mItems.size();
692 }
693
694 /** {@inheritDoc} */
695 public MenuItem getItem(int index) {
696 return mItems.get(index);
697 }
698
699 public boolean isShortcutKey(int keyCode, KeyEvent event) {
700 return findItemWithShortcutForKey(keyCode, event) != null;
701 }
702
703 public void setQwertyMode(boolean isQwerty) {
704 mQwertyMode = isQwerty;
Adam Powell696cba52011-03-29 10:38:16 -0700705
706 onItemsChanged(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 }
708
709 /**
710 * Returns the ordering across all items. This will grab the category from
711 * the upper bits, find out how to order the category with respect to other
712 * categories, and combine it with the lower bits.
713 *
714 * @param categoryOrder The category order for a particular item (if it has
715 * not been or/add with a category, the default category is
716 * assumed).
717 * @return An ordering integer that can be used to order this item across
718 * all the items (even from other categories).
719 */
Adam Powell696cba52011-03-29 10:38:16 -0700720 private static int getOrdering(int categoryOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 final int index = (categoryOrder & CATEGORY_MASK) >> CATEGORY_SHIFT;
722
723 if (index < 0 || index >= sCategoryToOrder.length) {
724 throw new IllegalArgumentException("order does not contain a valid category.");
725 }
726
727 return (sCategoryToOrder[index] << CATEGORY_SHIFT) | (categoryOrder & USER_MASK);
728 }
729
730 /**
731 * @return whether the menu shortcuts are in qwerty mode or not
732 */
733 boolean isQwertyMode() {
734 return mQwertyMode;
735 }
736
737 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 * Sets whether the shortcuts should be visible on menus. Devices without hardware
739 * key input will never make shortcuts visible even if this method is passed 'true'.
740 *
741 * @param shortcutsVisible Whether shortcuts should be visible (if true and a
742 * menu item does not have a shortcut defined, that item will
743 * still NOT show a shortcut)
744 */
745 public void setShortcutsVisible(boolean shortcutsVisible) {
746 if (mShortcutsVisible == shortcutsVisible) return;
Jeff Brown4aed78b2011-01-14 17:36:55 -0800747
748 setShortcutsVisibleInner(shortcutsVisible);
Adam Powell696cba52011-03-29 10:38:16 -0700749 onItemsChanged(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 }
751
Jeff Brown4aed78b2011-01-14 17:36:55 -0800752 private void setShortcutsVisibleInner(boolean shortcutsVisible) {
753 mShortcutsVisible = shortcutsVisible
754 && mResources.getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS
755 && mResources.getBoolean(
756 com.android.internal.R.bool.config_showMenuShortcutsWhenKeyboardPresent);
757 }
758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 /**
760 * @return Whether shortcuts should be visible on menus.
761 */
762 public boolean isShortcutsVisible() {
763 return mShortcutsVisible;
764 }
765
766 Resources getResources() {
767 return mResources;
768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769
770 public Context getContext() {
771 return mContext;
772 }
773
Adam Powell696cba52011-03-29 10:38:16 -0700774 boolean dispatchMenuItemSelected(MenuBuilder menu, MenuItem item) {
775 return mCallback != null && mCallback.onMenuItemSelected(menu, item);
776 }
777
778 /**
779 * Dispatch a mode change event to this menu's callback.
780 */
781 public void changeMenuMode() {
782 if (mCallback != null) {
783 mCallback.onMenuModeChange(this);
784 }
785 }
786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 private static int findInsertIndex(ArrayList<MenuItemImpl> items, int ordering) {
788 for (int i = items.size() - 1; i >= 0; i--) {
789 MenuItemImpl item = items.get(i);
790 if (item.getOrdering() <= ordering) {
791 return i + 1;
792 }
793 }
794
795 return 0;
796 }
797
798 public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
799 final MenuItemImpl item = findItemWithShortcutForKey(keyCode, event);
800
801 boolean handled = false;
802
803 if (item != null) {
804 handled = performItemAction(item, flags);
805 }
806
807 if ((flags & FLAG_ALWAYS_PERFORM_CLOSE) != 0) {
Alan Viverette00aa5102015-11-03 13:03:15 -0500808 close(true /* closeAllMenus */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 }
810
811 return handled;
812 }
813
Nicolas Roarde0fc8382009-09-24 21:30:06 +0100814 /*
815 * This function will return all the menu and sub-menu items that can
816 * be directly (the shortcut directly corresponds) and indirectly
817 * (the ALT-enabled char corresponds to the shortcut) associated
818 * with the keyCode.
819 */
Adam Powell696cba52011-03-29 10:38:16 -0700820 void findItemsWithShortcutForKey(List<MenuItemImpl> items, int keyCode, KeyEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 final boolean qwerty = isQwertyMode();
Peeyush Agarwale631e322016-10-19 11:41:42 +0100822 final int modifierState = event.getModifiers();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
824 // Get the chars associated with the keyCode (i.e using any chording combo)
825 final boolean isKeyCodeMapped = event.getKeyData(possibleChars);
826 // The delete key is not mapped to '\b' so we treat it specially
827 if (!isKeyCodeMapped && (keyCode != KeyEvent.KEYCODE_DEL)) {
Adam Powell696cba52011-03-29 10:38:16 -0700828 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
830
831 // Look for an item whose shortcut is this key.
832 final int N = mItems.size();
833 for (int i = 0; i < N; i++) {
834 MenuItemImpl item = mItems.get(i);
835 if (item.hasSubMenu()) {
Adam Powell696cba52011-03-29 10:38:16 -0700836 ((MenuBuilder)item.getSubMenu()).findItemsWithShortcutForKey(items, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
Peeyush Agarwale631e322016-10-19 11:41:42 +0100838 final char shortcutChar =
839 qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut();
840 final int shortcutModifiers =
841 qwerty ? item.getAlphabeticModifiers() : item.getNumericModifiers();
842 final boolean isModifiersExactMatch = (modifierState & SUPPORTED_MODIFIERS_MASK)
843 == (shortcutModifiers & SUPPORTED_MODIFIERS_MASK);
844 if (isModifiersExactMatch && (shortcutChar != 0) &&
Nicolas Roarde0fc8382009-09-24 21:30:06 +0100845 (shortcutChar == possibleChars.meta[0]
846 || shortcutChar == possibleChars.meta[2]
847 || (qwerty && shortcutChar == '\b' &&
848 keyCode == KeyEvent.KEYCODE_DEL)) &&
Alan Viverettee38eb4d2014-10-22 23:51:32 +0000849 item.isEnabled()) {
Nicolas Roarde0fc8382009-09-24 21:30:06 +0100850 items.add(item);
851 }
852 }
Nicolas Roarde0fc8382009-09-24 21:30:06 +0100853 }
854
855 /*
856 * We want to return the menu item associated with the key, but if there is no
857 * ambiguity (i.e. there is only one menu item corresponding to the key) we want
858 * to return it even if it's not an exact match; this allow the user to
859 * _not_ use the ALT key for example, making the use of shortcuts slightly more
860 * user-friendly. An example is on the G1, '!' and '1' are on the same key, and
861 * in Gmail, Menu+1 will trigger Menu+! (the actual shortcut).
862 *
863 * On the other hand, if two (or more) shortcuts corresponds to the same key,
864 * we have to only return the exact match.
865 */
866 MenuItemImpl findItemWithShortcutForKey(int keyCode, KeyEvent event) {
867 // Get all items that can be associated directly or indirectly with the keyCode
Adam Powell696cba52011-03-29 10:38:16 -0700868 ArrayList<MenuItemImpl> items = mTempShortcutItemList;
869 items.clear();
870 findItemsWithShortcutForKey(items, keyCode, event);
Nicolas Roarde0fc8382009-09-24 21:30:06 +0100871
Adam Powell696cba52011-03-29 10:38:16 -0700872 if (items.isEmpty()) {
Nicolas Roarde0fc8382009-09-24 21:30:06 +0100873 return null;
874 }
875
876 final int metaState = event.getMetaState();
877 final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
878 // Get the chars associated with the keyCode (i.e using any chording combo)
879 event.getKeyData(possibleChars);
880
881 // If we have only one element, we can safely returns it
Adam Powell696cba52011-03-29 10:38:16 -0700882 final int size = items.size();
883 if (size == 1) {
Nicolas Roarde0fc8382009-09-24 21:30:06 +0100884 return items.get(0);
885 }
886
887 final boolean qwerty = isQwertyMode();
888 // If we found more than one item associated with the key,
889 // we have to return the exact match
Adam Powell696cba52011-03-29 10:38:16 -0700890 for (int i = 0; i < size; i++) {
891 final MenuItemImpl item = items.get(i);
892 final char shortcutChar = qwerty ? item.getAlphabeticShortcut() :
893 item.getNumericShortcut();
Nicolas Roarde0fc8382009-09-24 21:30:06 +0100894 if ((shortcutChar == possibleChars.meta[0] &&
895 (metaState & KeyEvent.META_ALT_ON) == 0)
896 || (shortcutChar == possibleChars.meta[2] &&
897 (metaState & KeyEvent.META_ALT_ON) != 0)
898 || (qwerty && shortcutChar == '\b' &&
899 keyCode == KeyEvent.KEYCODE_DEL)) {
900 return item;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 }
902 }
903 return null;
904 }
Nicolas Roarde0fc8382009-09-24 21:30:06 +0100905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 public boolean performIdentifierAction(int id, int flags) {
907 // Look for an item whose identifier is the id.
908 return performItemAction(findItem(id), flags);
909 }
910
911 public boolean performItemAction(MenuItem item, int flags) {
Adam Powellc0cc6802013-12-03 18:58:29 -0800912 return performItemAction(item, null, flags);
913 }
914
915 public boolean performItemAction(MenuItem item, MenuPresenter preferredPresenter, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 MenuItemImpl itemImpl = (MenuItemImpl) item;
917
918 if (itemImpl == null || !itemImpl.isEnabled()) {
919 return false;
Adam Powell8d02dea2011-05-31 21:35:13 -0700920 }
Svetoslav Ganov76559a62011-07-06 17:17:52 -0700921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 boolean invoked = itemImpl.invoke();
923
Adam Powellf77f4802012-05-14 16:44:43 -0700924 final ActionProvider provider = item.getActionProvider();
925 final boolean providerHasSubMenu = provider != null && provider.hasSubMenu();
Adam Powell8d02dea2011-05-31 21:35:13 -0700926 if (itemImpl.hasCollapsibleActionView()) {
927 invoked |= itemImpl.expandActionView();
Alan Viverette00aa5102015-11-03 13:03:15 -0500928 if (invoked) {
929 close(true /* closeAllMenus */);
930 }
Adam Powellf77f4802012-05-14 16:44:43 -0700931 } else if (itemImpl.hasSubMenu() || providerHasSubMenu) {
Adam Powellf77f4802012-05-14 16:44:43 -0700932 if (!itemImpl.hasSubMenu()) {
933 itemImpl.setSubMenu(new SubMenuBuilder(getContext(), this, itemImpl));
934 }
935
936 final SubMenuBuilder subMenu = (SubMenuBuilder) itemImpl.getSubMenu();
937 if (providerHasSubMenu) {
Adam Powell961dd112011-07-12 14:25:23 -0700938 provider.onPrepareSubMenu(subMenu);
939 }
Adam Powellc0cc6802013-12-03 18:58:29 -0800940 invoked |= dispatchSubMenuSelected(subMenu, preferredPresenter);
Alan Viverette00aa5102015-11-03 13:03:15 -0500941 if (!invoked) {
942 close(true /* closeAllMenus */);
943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 } else {
945 if ((flags & FLAG_PERFORM_NO_CLOSE) == 0) {
Alan Viverette00aa5102015-11-03 13:03:15 -0500946 close(true /* closeAllMenus */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
948 }
949
950 return invoked;
951 }
952
953 /**
Alan Viverette00aa5102015-11-03 13:03:15 -0500954 * Closes the menu.
955 *
956 * @param closeAllMenus {@code true} if all displayed menus and submenus
957 * should be completely closed (as when a menu item is
958 * selected) or {@code false} if only this menu should
959 * be closed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 */
Alan Viverette00aa5102015-11-03 13:03:15 -0500961 public final void close(boolean closeAllMenus) {
Adam Powell696cba52011-03-29 10:38:16 -0700962 if (mIsClosing) return;
963
964 mIsClosing = true;
965 for (WeakReference<MenuPresenter> ref : mPresenters) {
966 final MenuPresenter presenter = ref.get();
967 if (presenter == null) {
968 mPresenters.remove(ref);
969 } else {
Alan Viverette00aa5102015-11-03 13:03:15 -0500970 presenter.onCloseMenu(this, closeAllMenus);
Adam Powell696cba52011-03-29 10:38:16 -0700971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
Adam Powell696cba52011-03-29 10:38:16 -0700973 mIsClosing = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 }
975
976 /** {@inheritDoc} */
977 public void close() {
Alan Viverette00aa5102015-11-03 13:03:15 -0500978 close(true /* closeAllMenus */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 }
980
981 /**
982 * Called when an item is added or removed.
983 *
Adam Powell696cba52011-03-29 10:38:16 -0700984 * @param structureChanged true if the menu structure changed,
985 * false if only item properties changed.
Adam Powell23f4cc02011-08-18 10:30:46 -0700986 * (Visibility is a structural property since it affects layout.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 */
Adam Powellfa18d182014-01-07 15:56:59 -0800988 public void onItemsChanged(boolean structureChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 if (!mPreventDispatchingItemsChanged) {
Adam Powell696cba52011-03-29 10:38:16 -0700990 if (structureChanged) {
991 mIsVisibleItemsStale = true;
992 mIsActionItemsStale = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
Adam Powell696cba52011-03-29 10:38:16 -0700994
995 dispatchPresenterUpdate(structureChanged);
996 } else {
997 mItemsChangedWhileDispatchPrevented = true;
998 }
999 }
1000
1001 /**
1002 * Stop dispatching item changed events to presenters until
1003 * {@link #startDispatchingItemsChanged()} is called. Useful when
1004 * many menu operations are going to be performed as a batch.
1005 */
1006 public void stopDispatchingItemsChanged() {
Adam Powella86b3502011-04-21 14:49:23 -07001007 if (!mPreventDispatchingItemsChanged) {
1008 mPreventDispatchingItemsChanged = true;
1009 mItemsChangedWhileDispatchPrevented = false;
1010 }
Adam Powell696cba52011-03-29 10:38:16 -07001011 }
1012
1013 public void startDispatchingItemsChanged() {
1014 mPreventDispatchingItemsChanged = false;
1015
1016 if (mItemsChangedWhileDispatchPrevented) {
1017 mItemsChangedWhileDispatchPrevented = false;
1018 onItemsChanged(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 }
1020 }
1021
1022 /**
1023 * Called by {@link MenuItemImpl} when its visible flag is changed.
1024 * @param item The item that has gone through a visibility change.
1025 */
1026 void onItemVisibleChanged(MenuItemImpl item) {
1027 // Notify of items being changed
Adam Powell696cba52011-03-29 10:38:16 -07001028 mIsVisibleItemsStale = true;
Adam Powell23f4cc02011-08-18 10:30:46 -07001029 onItemsChanged(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
1031
Adam Powell96675b12010-06-10 18:58:59 -07001032 /**
1033 * Called by {@link MenuItemImpl} when its action request status is changed.
1034 * @param item The item that has gone through a change in action request status.
1035 */
1036 void onItemActionRequestChanged(MenuItemImpl item) {
1037 // Notify of items being changed
Adam Powell696cba52011-03-29 10:38:16 -07001038 mIsActionItemsStale = true;
Adam Powell23f4cc02011-08-18 10:30:46 -07001039 onItemsChanged(true);
Adam Powell96675b12010-06-10 18:58:59 -07001040 }
Alan Viverette28a84682016-01-04 13:43:23 -05001041
1042 @NonNull
Adam Powellfa18d182014-01-07 15:56:59 -08001043 public ArrayList<MenuItemImpl> getVisibleItems() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 if (!mIsVisibleItemsStale) return mVisibleItems;
Alan Viverette28a84682016-01-04 13:43:23 -05001045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 // Refresh the visible items
1047 mVisibleItems.clear();
Alan Viverette28a84682016-01-04 13:43:23 -05001048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 final int itemsSize = mItems.size();
1050 MenuItemImpl item;
1051 for (int i = 0; i < itemsSize; i++) {
1052 item = mItems.get(i);
1053 if (item.isVisible()) mVisibleItems.add(item);
1054 }
Alan Viverette28a84682016-01-04 13:43:23 -05001055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 mIsVisibleItemsStale = false;
Adam Powell96675b12010-06-10 18:58:59 -07001057 mIsActionItemsStale = true;
Alan Viverette28a84682016-01-04 13:43:23 -05001058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 return mVisibleItems;
1060 }
Adam Powell36fced92011-01-16 15:48:07 -08001061
1062 /**
1063 * This method determines which menu items get to be 'action items' that will appear
1064 * in an action bar and which items should be 'overflow items' in a secondary menu.
1065 * The rules are as follows:
1066 *
1067 * <p>Items are considered for inclusion in the order specified within the menu.
1068 * There is a limit of mMaxActionItems as a total count, optionally including the overflow
1069 * menu button itself. This is a soft limit; if an item shares a group ID with an item
1070 * previously included as an action item, the new item will stay with its group and become
1071 * an action item itself even if it breaks the max item count limit. This is done to
1072 * limit the conceptual complexity of the items presented within an action bar. Only a few
1073 * unrelated concepts should be presented to the user in this space, and groups are treated
1074 * as a single concept.
1075 *
1076 * <p>There is also a hard limit of consumed measurable space: mActionWidthLimit. This
1077 * limit may be broken by a single item that exceeds the remaining space, but no further
1078 * items may be added. If an item that is part of a group cannot fit within the remaining
1079 * measured width, the entire group will be demoted to overflow. This is done to ensure room
1080 * for navigation and other affordances in the action bar as well as reduce general UI clutter.
1081 *
1082 * <p>The space freed by demoting a full group cannot be consumed by future menu items.
1083 * Once items begin to overflow, all future items become overflow items as well. This is
1084 * to avoid inadvertent reordering that may break the app's intended design.
Adam Powell36fced92011-01-16 15:48:07 -08001085 */
Adam Powell696cba52011-03-29 10:38:16 -07001086 public void flagActionItems() {
Adam Powellda971082013-10-03 18:21:58 -07001087 // Important side effect: if getVisibleItems is stale it may refresh,
1088 // which can affect action items staleness.
1089 final ArrayList<MenuItemImpl> visibleItems = getVisibleItems();
1090
Adam Powell96675b12010-06-10 18:58:59 -07001091 if (!mIsActionItemsStale) {
1092 return;
1093 }
Adam Powell8028dd32010-07-15 10:16:33 -07001094
Adam Powell696cba52011-03-29 10:38:16 -07001095 // Presenters flag action items as needed.
1096 boolean flagged = false;
1097 for (WeakReference<MenuPresenter> ref : mPresenters) {
1098 final MenuPresenter presenter = ref.get();
1099 if (presenter == null) {
1100 mPresenters.remove(ref);
Adam Powell8028dd32010-07-15 10:16:33 -07001101 } else {
Adam Powell696cba52011-03-29 10:38:16 -07001102 flagged |= presenter.flagActionItems();
Adam Powell96675b12010-06-10 18:58:59 -07001103 }
1104 }
Adam Powell8028dd32010-07-15 10:16:33 -07001105
Adam Powell696cba52011-03-29 10:38:16 -07001106 if (flagged) {
1107 mActionItems.clear();
1108 mNonActionItems.clear();
Adam Powell696cba52011-03-29 10:38:16 -07001109 final int itemsSize = visibleItems.size();
1110 for (int i = 0; i < itemsSize; i++) {
1111 MenuItemImpl item = visibleItems.get(i);
1112 if (item.isActionButton()) {
1113 mActionItems.add(item);
1114 } else {
1115 mNonActionItems.add(item);
Adam Powell36fced92011-01-16 15:48:07 -08001116 }
Adam Powell96675b12010-06-10 18:58:59 -07001117 }
Adam Powell04dc06f2011-08-22 18:11:11 -07001118 } else {
1119 // Nobody flagged anything, everything is a non-action item.
Adam Powell696cba52011-03-29 10:38:16 -07001120 // (This happens during a first pass with no action-item presenters.)
1121 mActionItems.clear();
1122 mNonActionItems.clear();
1123 mNonActionItems.addAll(getVisibleItems());
Adam Powell96675b12010-06-10 18:58:59 -07001124 }
Adam Powell96675b12010-06-10 18:58:59 -07001125 mIsActionItemsStale = false;
1126 }
1127
Adam Powellfa18d182014-01-07 15:56:59 -08001128 public ArrayList<MenuItemImpl> getActionItems() {
Adam Powell696cba52011-03-29 10:38:16 -07001129 flagActionItems();
Adam Powell96675b12010-06-10 18:58:59 -07001130 return mActionItems;
1131 }
1132
Adam Powellfa18d182014-01-07 15:56:59 -08001133 public ArrayList<MenuItemImpl> getNonActionItems() {
Adam Powell696cba52011-03-29 10:38:16 -07001134 flagActionItems();
Adam Powell96675b12010-06-10 18:58:59 -07001135 return mNonActionItems;
1136 }
Adam Powell36fced92011-01-16 15:48:07 -08001137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 public void clearHeader() {
1139 mHeaderIcon = null;
1140 mHeaderTitle = null;
1141 mHeaderView = null;
1142
1143 onItemsChanged(false);
1144 }
1145
1146 private void setHeaderInternal(final int titleRes, final CharSequence title, final int iconRes,
1147 final Drawable icon, final View view) {
1148 final Resources r = getResources();
1149
1150 if (view != null) {
1151 mHeaderView = view;
1152
1153 // If using a custom view, then the title and icon aren't used
1154 mHeaderTitle = null;
1155 mHeaderIcon = null;
1156 } else {
1157 if (titleRes > 0) {
1158 mHeaderTitle = r.getText(titleRes);
1159 } else if (title != null) {
1160 mHeaderTitle = title;
1161 }
1162
1163 if (iconRes > 0) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001164 mHeaderIcon = getContext().getDrawable(iconRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 } else if (icon != null) {
1166 mHeaderIcon = icon;
1167 }
1168
1169 // If using the title or icon, then a custom view isn't used
1170 mHeaderView = null;
1171 }
1172
1173 // Notify of change
1174 onItemsChanged(false);
1175 }
1176
1177 /**
1178 * Sets the header's title. This replaces the header view. Called by the
1179 * builder-style methods of subclasses.
1180 *
1181 * @param title The new title.
1182 * @return This MenuBuilder so additional setters can be called.
1183 */
1184 protected MenuBuilder setHeaderTitleInt(CharSequence title) {
1185 setHeaderInternal(0, title, 0, null, null);
1186 return this;
1187 }
1188
1189 /**
1190 * Sets the header's title. This replaces the header view. Called by the
1191 * builder-style methods of subclasses.
1192 *
1193 * @param titleRes The new title (as a resource ID).
1194 * @return This MenuBuilder so additional setters can be called.
1195 */
1196 protected MenuBuilder setHeaderTitleInt(int titleRes) {
1197 setHeaderInternal(titleRes, null, 0, null, null);
1198 return this;
1199 }
1200
1201 /**
1202 * Sets the header's icon. This replaces the header view. Called by the
1203 * builder-style methods of subclasses.
1204 *
1205 * @param icon The new icon.
1206 * @return This MenuBuilder so additional setters can be called.
1207 */
1208 protected MenuBuilder setHeaderIconInt(Drawable icon) {
1209 setHeaderInternal(0, null, 0, icon, null);
1210 return this;
1211 }
1212
1213 /**
1214 * Sets the header's icon. This replaces the header view. Called by the
1215 * builder-style methods of subclasses.
1216 *
1217 * @param iconRes The new icon (as a resource ID).
1218 * @return This MenuBuilder so additional setters can be called.
1219 */
1220 protected MenuBuilder setHeaderIconInt(int iconRes) {
1221 setHeaderInternal(0, null, iconRes, null, null);
1222 return this;
1223 }
1224
1225 /**
1226 * Sets the header's view. This replaces the title and icon. Called by the
1227 * builder-style methods of subclasses.
1228 *
1229 * @param view The new view.
1230 * @return This MenuBuilder so additional setters can be called.
1231 */
1232 protected MenuBuilder setHeaderViewInt(View view) {
1233 setHeaderInternal(0, null, 0, null, view);
1234 return this;
1235 }
1236
1237 public CharSequence getHeaderTitle() {
1238 return mHeaderTitle;
1239 }
1240
1241 public Drawable getHeaderIcon() {
1242 return mHeaderIcon;
1243 }
1244
1245 public View getHeaderView() {
1246 return mHeaderView;
1247 }
1248
1249 /**
1250 * Gets the root menu (if this is a submenu, find its root menu).
1251 * @return The root menu.
1252 */
1253 public MenuBuilder getRootMenu() {
1254 return this;
1255 }
1256
1257 /**
1258 * Sets the current menu info that is set on all items added to this menu
1259 * (until this is called again with different menu info, in which case that
1260 * one will be added to all subsequent item additions).
1261 *
1262 * @param menuInfo The extra menu information to add.
1263 */
1264 public void setCurrentMenuInfo(ContextMenuInfo menuInfo) {
1265 mCurrentMenuInfo = menuInfo;
1266 }
1267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 void setOptionalIconsVisible(boolean visible) {
1269 mOptionalIconsVisible = visible;
1270 }
1271
1272 boolean getOptionalIconsVisible() {
1273 return mOptionalIconsVisible;
1274 }
Adam Powell8d02dea2011-05-31 21:35:13 -07001275
1276 public boolean expandItemActionView(MenuItemImpl item) {
1277 if (mPresenters.isEmpty()) return false;
1278
1279 boolean expanded = false;
1280
1281 stopDispatchingItemsChanged();
1282 for (WeakReference<MenuPresenter> ref : mPresenters) {
1283 final MenuPresenter presenter = ref.get();
1284 if (presenter == null) {
1285 mPresenters.remove(ref);
1286 } else if ((expanded = presenter.expandItemActionView(this, item))) {
1287 break;
1288 }
1289 }
1290 startDispatchingItemsChanged();
1291
Adam Powell6b0e97c2011-08-03 12:06:32 -07001292 if (expanded) {
1293 mExpandedItem = item;
1294 }
Adam Powell8d02dea2011-05-31 21:35:13 -07001295 return expanded;
1296 }
1297
1298 public boolean collapseItemActionView(MenuItemImpl item) {
Adam Powell6b0e97c2011-08-03 12:06:32 -07001299 if (mPresenters.isEmpty() || mExpandedItem != item) return false;
Adam Powell8d02dea2011-05-31 21:35:13 -07001300
1301 boolean collapsed = false;
1302
1303 stopDispatchingItemsChanged();
1304 for (WeakReference<MenuPresenter> ref : mPresenters) {
1305 final MenuPresenter presenter = ref.get();
1306 if (presenter == null) {
1307 mPresenters.remove(ref);
1308 } else if ((collapsed = presenter.collapseItemActionView(this, item))) {
1309 break;
1310 }
1311 }
1312 startDispatchingItemsChanged();
1313
Adam Powell6b0e97c2011-08-03 12:06:32 -07001314 if (collapsed) {
1315 mExpandedItem = null;
1316 }
Adam Powell8d02dea2011-05-31 21:35:13 -07001317 return collapsed;
1318 }
Adam Powell275702c2011-09-23 17:34:04 -07001319
1320 public MenuItemImpl getExpandedItem() {
1321 return mExpandedItem;
1322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323}