MenuInflater.java revision 1001961f904bac5294aaf73a47c2497aa764bf7f
1/* 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 android.view; 18 19import com.android.internal.view.menu.MenuItemImpl; 20 21import org.xmlpull.v1.XmlPullParser; 22import org.xmlpull.v1.XmlPullParserException; 23 24import android.app.Activity; 25import android.content.Context; 26import android.content.res.TypedArray; 27import android.content.res.XmlResourceParser; 28import android.util.AttributeSet; 29import android.util.Log; 30import android.util.Xml; 31 32import java.io.IOException; 33import java.lang.reflect.Constructor; 34import java.lang.reflect.Method; 35 36/** 37 * This class is used to instantiate menu XML files into Menu objects. 38 * <p> 39 * For performance reasons, menu inflation relies heavily on pre-processing of 40 * XML files that is done at build time. Therefore, it is not currently possible 41 * to use MenuInflater with an XmlPullParser over a plain XML file at runtime; 42 * it only works with an XmlPullParser returned from a compiled resource (R. 43 * <em>something</em> file.) 44 */ 45public class MenuInflater { 46 private static final String LOG_TAG = "MenuInflater"; 47 48 /** Menu tag name in XML. */ 49 private static final String XML_MENU = "menu"; 50 51 /** Group tag name in XML. */ 52 private static final String XML_GROUP = "group"; 53 54 /** Item tag name in XML. */ 55 private static final String XML_ITEM = "item"; 56 57 private static final int NO_ID = 0; 58 59 private static final Class<?>[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE = new Class[] {Context.class}; 60 61 private static final Class<?>[] ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE = ACTION_VIEW_CONSTRUCTOR_SIGNATURE; 62 63 private final Object[] mActionViewConstructorArguments; 64 65 private final Object[] mActionProviderConstructorArguments; 66 67 private Context mContext; 68 private Object mRealOwner; 69 70 /** 71 * Constructs a menu inflater. 72 * 73 * @see Activity#getMenuInflater() 74 */ 75 public MenuInflater(Context context) { 76 mContext = context; 77 mRealOwner = context; 78 mActionViewConstructorArguments = new Object[] {context}; 79 mActionProviderConstructorArguments = mActionViewConstructorArguments; 80 } 81 82 /** 83 * Constructs a menu inflater. 84 * 85 * @see Activity#getMenuInflater() 86 * @hide 87 */ 88 public MenuInflater(Context context, Object realOwner) { 89 mContext = context; 90 mRealOwner = realOwner; 91 mActionViewConstructorArguments = new Object[] {context}; 92 mActionProviderConstructorArguments = mActionViewConstructorArguments; 93 } 94 95 /** 96 * Inflate a menu hierarchy from the specified XML resource. Throws 97 * {@link InflateException} if there is an error. 98 * 99 * @param menuRes Resource ID for an XML layout resource to load (e.g., 100 * <code>R.menu.main_activity</code>) 101 * @param menu The Menu to inflate into. The items and submenus will be 102 * added to this Menu. 103 */ 104 public void inflate(int menuRes, Menu menu) { 105 XmlResourceParser parser = null; 106 try { 107 parser = mContext.getResources().getLayout(menuRes); 108 AttributeSet attrs = Xml.asAttributeSet(parser); 109 110 parseMenu(parser, attrs, menu); 111 } catch (XmlPullParserException e) { 112 throw new InflateException("Error inflating menu XML", e); 113 } catch (IOException e) { 114 throw new InflateException("Error inflating menu XML", e); 115 } finally { 116 if (parser != null) parser.close(); 117 } 118 } 119 120 /** 121 * Called internally to fill the given menu. If a sub menu is seen, it will 122 * call this recursively. 123 */ 124 private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu) 125 throws XmlPullParserException, IOException { 126 MenuState menuState = new MenuState(menu); 127 128 int eventType = parser.getEventType(); 129 String tagName; 130 boolean lookingForEndOfUnknownTag = false; 131 String unknownTagName = null; 132 133 // This loop will skip to the menu start tag 134 do { 135 if (eventType == XmlPullParser.START_TAG) { 136 tagName = parser.getName(); 137 if (tagName.equals(XML_MENU)) { 138 // Go to next tag 139 eventType = parser.next(); 140 break; 141 } 142 143 throw new RuntimeException("Expecting menu, got " + tagName); 144 } 145 eventType = parser.next(); 146 } while (eventType != XmlPullParser.END_DOCUMENT); 147 148 boolean reachedEndOfMenu = false; 149 while (!reachedEndOfMenu) { 150 switch (eventType) { 151 case XmlPullParser.START_TAG: 152 if (lookingForEndOfUnknownTag) { 153 break; 154 } 155 156 tagName = parser.getName(); 157 if (tagName.equals(XML_GROUP)) { 158 menuState.readGroup(attrs); 159 } else if (tagName.equals(XML_ITEM)) { 160 menuState.readItem(attrs); 161 } else if (tagName.equals(XML_MENU)) { 162 // A menu start tag denotes a submenu for an item 163 SubMenu subMenu = menuState.addSubMenuItem(); 164 registerMenu(subMenu, attrs); 165 166 // Parse the submenu into returned SubMenu 167 parseMenu(parser, attrs, subMenu); 168 } else { 169 lookingForEndOfUnknownTag = true; 170 unknownTagName = tagName; 171 } 172 break; 173 174 case XmlPullParser.END_TAG: 175 tagName = parser.getName(); 176 if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) { 177 lookingForEndOfUnknownTag = false; 178 unknownTagName = null; 179 } else if (tagName.equals(XML_GROUP)) { 180 menuState.resetGroup(); 181 } else if (tagName.equals(XML_ITEM)) { 182 // Add the item if it hasn't been added (if the item was 183 // a submenu, it would have been added already) 184 if (!menuState.hasAddedItem()) { 185 if (menuState.itemActionProvider != null && 186 menuState.itemActionProvider.hasSubMenu()) { 187 registerMenu(menuState.addSubMenuItem(), attrs); 188 } else { 189 registerMenu(menuState.addItem(), attrs); 190 } 191 } 192 } else if (tagName.equals(XML_MENU)) { 193 reachedEndOfMenu = true; 194 } 195 break; 196 197 case XmlPullParser.END_DOCUMENT: 198 throw new RuntimeException("Unexpected end of document"); 199 } 200 201 eventType = parser.next(); 202 } 203 } 204 205 /** 206 * The method is a hook for layoutlib to do its magic. 207 * Nothing is needed outside of LayoutLib. However, it should not be deleted because it 208 * appears to do nothing. 209 */ 210 private void registerMenu(@SuppressWarnings("unused") MenuItem item, 211 @SuppressWarnings("unused") AttributeSet set) { 212 } 213 214 /** 215 * The method is a hook for layoutlib to do its magic. 216 * Nothing is needed outside of LayoutLib. However, it should not be deleted because it 217 * appears to do nothing. 218 */ 219 private void registerMenu(@SuppressWarnings("unused") SubMenu subMenu, 220 @SuppressWarnings("unused") AttributeSet set) { 221 } 222 223 // Needed by layoutlib. 224 /*package*/ Context getContext() { 225 return mContext; 226 } 227 228 private static class InflatedOnMenuItemClickListener 229 implements MenuItem.OnMenuItemClickListener { 230 private static final Class<?>[] PARAM_TYPES = new Class[] { MenuItem.class }; 231 232 private Object mRealOwner; 233 private Method mMethod; 234 235 public InflatedOnMenuItemClickListener(Object realOwner, String methodName) { 236 mRealOwner = realOwner; 237 Class<?> c = realOwner.getClass(); 238 try { 239 mMethod = c.getMethod(methodName, PARAM_TYPES); 240 } catch (Exception e) { 241 InflateException ex = new InflateException( 242 "Couldn't resolve menu item onClick handler " + methodName + 243 " in class " + c.getName()); 244 ex.initCause(e); 245 throw ex; 246 } 247 } 248 249 public boolean onMenuItemClick(MenuItem item) { 250 try { 251 if (mMethod.getReturnType() == Boolean.TYPE) { 252 return (Boolean) mMethod.invoke(mRealOwner, item); 253 } else { 254 mMethod.invoke(mRealOwner, item); 255 return true; 256 } 257 } catch (Exception e) { 258 throw new RuntimeException(e); 259 } 260 } 261 } 262 263 /** 264 * State for the current menu. 265 * <p> 266 * Groups can not be nested unless there is another menu (which will have 267 * its state class). 268 */ 269 private class MenuState { 270 private Menu menu; 271 272 /* 273 * Group state is set on items as they are added, allowing an item to 274 * override its group state. (As opposed to set on items at the group end tag.) 275 */ 276 private int groupId; 277 private int groupCategory; 278 private int groupOrder; 279 private int groupCheckable; 280 private boolean groupVisible; 281 private boolean groupEnabled; 282 283 private boolean itemAdded; 284 private int itemId; 285 private int itemCategoryOrder; 286 private CharSequence itemTitle; 287 private CharSequence itemTitleCondensed; 288 private int itemIconResId; 289 private char itemAlphabeticShortcut; 290 private char itemNumericShortcut; 291 /** 292 * Sync to attrs.xml enum: 293 * - 0: none 294 * - 1: all 295 * - 2: exclusive 296 */ 297 private int itemCheckable; 298 private boolean itemChecked; 299 private boolean itemVisible; 300 private boolean itemEnabled; 301 302 /** 303 * Sync to attrs.xml enum, values in MenuItem: 304 * - 0: never 305 * - 1: ifRoom 306 * - 2: always 307 * - -1: Safe sentinel for "no value". 308 */ 309 private int itemShowAsAction; 310 311 private int itemActionViewLayout; 312 private String itemActionViewClassName; 313 private String itemActionProviderClassName; 314 315 private String itemListenerMethodName; 316 317 private ActionProvider itemActionProvider; 318 319 private static final int defaultGroupId = NO_ID; 320 private static final int defaultItemId = NO_ID; 321 private static final int defaultItemCategory = 0; 322 private static final int defaultItemOrder = 0; 323 private static final int defaultItemCheckable = 0; 324 private static final boolean defaultItemChecked = false; 325 private static final boolean defaultItemVisible = true; 326 private static final boolean defaultItemEnabled = true; 327 328 public MenuState(final Menu menu) { 329 this.menu = menu; 330 331 resetGroup(); 332 } 333 334 public void resetGroup() { 335 groupId = defaultGroupId; 336 groupCategory = defaultItemCategory; 337 groupOrder = defaultItemOrder; 338 groupCheckable = defaultItemCheckable; 339 groupVisible = defaultItemVisible; 340 groupEnabled = defaultItemEnabled; 341 } 342 343 /** 344 * Called when the parser is pointing to a group tag. 345 */ 346 public void readGroup(AttributeSet attrs) { 347 TypedArray a = mContext.obtainStyledAttributes(attrs, 348 com.android.internal.R.styleable.MenuGroup); 349 350 groupId = a.getResourceId(com.android.internal.R.styleable.MenuGroup_id, defaultGroupId); 351 groupCategory = a.getInt(com.android.internal.R.styleable.MenuGroup_menuCategory, defaultItemCategory); 352 groupOrder = a.getInt(com.android.internal.R.styleable.MenuGroup_orderInCategory, defaultItemOrder); 353 groupCheckable = a.getInt(com.android.internal.R.styleable.MenuGroup_checkableBehavior, defaultItemCheckable); 354 groupVisible = a.getBoolean(com.android.internal.R.styleable.MenuGroup_visible, defaultItemVisible); 355 groupEnabled = a.getBoolean(com.android.internal.R.styleable.MenuGroup_enabled, defaultItemEnabled); 356 357 a.recycle(); 358 } 359 360 /** 361 * Called when the parser is pointing to an item tag. 362 */ 363 public void readItem(AttributeSet attrs) { 364 TypedArray a = mContext.obtainStyledAttributes(attrs, 365 com.android.internal.R.styleable.MenuItem); 366 367 // Inherit attributes from the group as default value 368 itemId = a.getResourceId(com.android.internal.R.styleable.MenuItem_id, defaultItemId); 369 final int category = a.getInt(com.android.internal.R.styleable.MenuItem_menuCategory, groupCategory); 370 final int order = a.getInt(com.android.internal.R.styleable.MenuItem_orderInCategory, groupOrder); 371 itemCategoryOrder = (category & Menu.CATEGORY_MASK) | (order & Menu.USER_MASK); 372 itemTitle = a.getText(com.android.internal.R.styleable.MenuItem_title); 373 itemTitleCondensed = a.getText(com.android.internal.R.styleable.MenuItem_titleCondensed); 374 itemIconResId = a.getResourceId(com.android.internal.R.styleable.MenuItem_icon, 0); 375 itemAlphabeticShortcut = 376 getShortcut(a.getString(com.android.internal.R.styleable.MenuItem_alphabeticShortcut)); 377 itemNumericShortcut = 378 getShortcut(a.getString(com.android.internal.R.styleable.MenuItem_numericShortcut)); 379 if (a.hasValue(com.android.internal.R.styleable.MenuItem_checkable)) { 380 // Item has attribute checkable, use it 381 itemCheckable = a.getBoolean(com.android.internal.R.styleable.MenuItem_checkable, false) ? 1 : 0; 382 } else { 383 // Item does not have attribute, use the group's (group can have one more state 384 // for checkable that represents the exclusive checkable) 385 itemCheckable = groupCheckable; 386 } 387 itemChecked = a.getBoolean(com.android.internal.R.styleable.MenuItem_checked, defaultItemChecked); 388 itemVisible = a.getBoolean(com.android.internal.R.styleable.MenuItem_visible, groupVisible); 389 itemEnabled = a.getBoolean(com.android.internal.R.styleable.MenuItem_enabled, groupEnabled); 390 itemShowAsAction = a.getInt(com.android.internal.R.styleable.MenuItem_showAsAction, -1); 391 itemListenerMethodName = a.getString(com.android.internal.R.styleable.MenuItem_onClick); 392 itemActionViewLayout = a.getResourceId(com.android.internal.R.styleable.MenuItem_actionLayout, 0); 393 itemActionViewClassName = a.getString(com.android.internal.R.styleable.MenuItem_actionViewClass); 394 itemActionProviderClassName = a.getString(com.android.internal.R.styleable.MenuItem_actionProviderClass); 395 396 final boolean hasActionProvider = itemActionProviderClassName != null; 397 if (hasActionProvider && itemActionViewLayout == 0 && itemActionViewClassName == null) { 398 itemActionProvider = newInstance(itemActionProviderClassName, 399 ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE, 400 mActionProviderConstructorArguments); 401 } else { 402 if (hasActionProvider) { 403 Log.w(LOG_TAG, "Ignoring attribute 'actionProviderClass'." 404 + " Action view already specified."); 405 } 406 itemActionProvider = null; 407 } 408 409 a.recycle(); 410 411 itemAdded = false; 412 } 413 414 private char getShortcut(String shortcutString) { 415 if (shortcutString == null) { 416 return 0; 417 } else { 418 return shortcutString.charAt(0); 419 } 420 } 421 422 private void setItem(MenuItem item) { 423 item.setChecked(itemChecked) 424 .setVisible(itemVisible) 425 .setEnabled(itemEnabled) 426 .setCheckable(itemCheckable >= 1) 427 .setTitleCondensed(itemTitleCondensed) 428 .setIcon(itemIconResId) 429 .setAlphabeticShortcut(itemAlphabeticShortcut) 430 .setNumericShortcut(itemNumericShortcut); 431 432 if (itemShowAsAction >= 0) { 433 item.setShowAsAction(itemShowAsAction); 434 } 435 436 if (itemListenerMethodName != null) { 437 if (mContext.isRestricted()) { 438 throw new IllegalStateException("The android:onClick attribute cannot " 439 + "be used within a restricted context"); 440 } 441 item.setOnMenuItemClickListener( 442 new InflatedOnMenuItemClickListener(mRealOwner, itemListenerMethodName)); 443 } 444 445 if (item instanceof MenuItemImpl) { 446 MenuItemImpl impl = (MenuItemImpl) item; 447 if (itemCheckable >= 2) { 448 impl.setExclusiveCheckable(true); 449 } 450 } 451 452 boolean actionViewSpecified = false; 453 if (itemActionViewClassName != null) { 454 View actionView = (View) newInstance(itemActionViewClassName, 455 ACTION_VIEW_CONSTRUCTOR_SIGNATURE, mActionViewConstructorArguments); 456 item.setActionView(actionView); 457 actionViewSpecified = true; 458 } 459 if (itemActionViewLayout > 0) { 460 if (!actionViewSpecified) { 461 item.setActionView(itemActionViewLayout); 462 actionViewSpecified = true; 463 } else { 464 Log.w(LOG_TAG, "Ignoring attribute 'itemActionViewLayout'." 465 + " Action view already specified."); 466 } 467 } 468 if (itemActionProvider != null) { 469 item.setActionProvider(itemActionProvider); 470 } 471 } 472 473 public MenuItem addItem() { 474 itemAdded = true; 475 MenuItem item = menu.add(groupId, itemId, itemCategoryOrder, itemTitle); 476 setItem(item); 477 return item; 478 } 479 480 public SubMenu addSubMenuItem() { 481 itemAdded = true; 482 SubMenu subMenu = menu.addSubMenu(groupId, itemId, itemCategoryOrder, itemTitle); 483 setItem(subMenu.getItem()); 484 return subMenu; 485 } 486 487 public boolean hasAddedItem() { 488 return itemAdded; 489 } 490 491 @SuppressWarnings("unchecked") 492 private <T> T newInstance(String className, Class<?>[] constructorSignature, 493 Object[] arguments) { 494 try { 495 Class<?> clazz = mContext.getClassLoader().loadClass(className); 496 Constructor<?> constructor = clazz.getConstructor(constructorSignature); 497 return (T) constructor.newInstance(arguments); 498 } catch (Exception e) { 499 Log.w(LOG_TAG, "Cannot instantiate class: " + className, e); 500 } 501 return null; 502 } 503 } 504} 505