MenuInflater.java revision 33b974393b6fadcefc896ec4a0f9b66724f61e9f
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 java.io.IOException; 20import java.lang.reflect.Method; 21 22import org.xmlpull.v1.XmlPullParser; 23import org.xmlpull.v1.XmlPullParserException; 24 25import android.app.Activity; 26import android.content.Context; 27import android.content.res.TypedArray; 28import android.content.res.XmlResourceParser; 29import android.util.AttributeSet; 30import android.util.Xml; 31 32import com.android.internal.view.menu.MenuItemImpl; 33 34/** 35 * This class is used to instantiate menu XML files into Menu objects. 36 * <p> 37 * For performance reasons, menu inflation relies heavily on pre-processing of 38 * XML files that is done at build time. Therefore, it is not currently possible 39 * to use MenuInflater with an XmlPullParser over a plain XML file at runtime; 40 * it only works with an XmlPullParser returned from a compiled resource (R. 41 * <em>something</em> file.) 42 */ 43public class MenuInflater { 44 /** Menu tag name in XML. */ 45 private static final String XML_MENU = "menu"; 46 47 /** Group tag name in XML. */ 48 private static final String XML_GROUP = "group"; 49 50 /** Item tag name in XML. */ 51 private static final String XML_ITEM = "item"; 52 53 private static final int NO_ID = 0; 54 55 private Context mContext; 56 57 /** 58 * Constructs a menu inflater. 59 * 60 * @see Activity#getMenuInflater() 61 */ 62 public MenuInflater(Context context) { 63 mContext = context; 64 } 65 66 /** 67 * Inflate a menu hierarchy from the specified XML resource. Throws 68 * {@link InflateException} if there is an error. 69 * 70 * @param menuRes Resource ID for an XML layout resource to load (e.g., 71 * <code>R.menu.main_activity</code>) 72 * @param menu The Menu to inflate into. The items and submenus will be 73 * added to this Menu. 74 */ 75 public void inflate(int menuRes, Menu menu) { 76 XmlResourceParser parser = null; 77 try { 78 parser = mContext.getResources().getLayout(menuRes); 79 AttributeSet attrs = Xml.asAttributeSet(parser); 80 81 parseMenu(parser, attrs, menu); 82 } catch (XmlPullParserException e) { 83 throw new InflateException("Error inflating menu XML", e); 84 } catch (IOException e) { 85 throw new InflateException("Error inflating menu XML", e); 86 } finally { 87 if (parser != null) parser.close(); 88 } 89 } 90 91 /** 92 * Called internally to fill the given menu. If a sub menu is seen, it will 93 * call this recursively. 94 */ 95 private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu) 96 throws XmlPullParserException, IOException { 97 MenuState menuState = new MenuState(menu); 98 99 int eventType = parser.getEventType(); 100 String tagName; 101 boolean lookingForEndOfUnknownTag = false; 102 String unknownTagName = null; 103 104 // This loop will skip to the menu start tag 105 do { 106 if (eventType == XmlPullParser.START_TAG) { 107 tagName = parser.getName(); 108 if (tagName.equals(XML_MENU)) { 109 // Go to next tag 110 eventType = parser.next(); 111 break; 112 } 113 114 throw new RuntimeException("Expecting menu, got " + tagName); 115 } 116 eventType = parser.next(); 117 } while (eventType != XmlPullParser.END_DOCUMENT); 118 119 boolean reachedEndOfMenu = false; 120 while (!reachedEndOfMenu) { 121 switch (eventType) { 122 case XmlPullParser.START_TAG: 123 if (lookingForEndOfUnknownTag) { 124 break; 125 } 126 127 tagName = parser.getName(); 128 if (tagName.equals(XML_GROUP)) { 129 menuState.readGroup(attrs); 130 } else if (tagName.equals(XML_ITEM)) { 131 menuState.readItem(attrs); 132 } else if (tagName.equals(XML_MENU)) { 133 // A menu start tag denotes a submenu for an item 134 SubMenu subMenu = menuState.addSubMenuItem(); 135 136 // Parse the submenu into returned SubMenu 137 parseMenu(parser, attrs, subMenu); 138 } else { 139 lookingForEndOfUnknownTag = true; 140 unknownTagName = tagName; 141 } 142 break; 143 144 case XmlPullParser.END_TAG: 145 tagName = parser.getName(); 146 if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) { 147 lookingForEndOfUnknownTag = false; 148 unknownTagName = null; 149 } else if (tagName.equals(XML_GROUP)) { 150 menuState.resetGroup(); 151 } else if (tagName.equals(XML_ITEM)) { 152 // Add the item if it hasn't been added (if the item was 153 // a submenu, it would have been added already) 154 if (!menuState.hasAddedItem()) { 155 menuState.addItem(); 156 } 157 } else if (tagName.equals(XML_MENU)) { 158 reachedEndOfMenu = true; 159 } 160 break; 161 162 case XmlPullParser.END_DOCUMENT: 163 throw new RuntimeException("Unexpected end of document"); 164 } 165 166 eventType = parser.next(); 167 } 168 } 169 170 private static class InflatedOnMenuItemClickListener 171 implements MenuItem.OnMenuItemClickListener { 172 private static final Class[] PARAM_TYPES = new Class[] { MenuItem.class }; 173 174 private Context mContext; 175 private Method mMethod; 176 177 public InflatedOnMenuItemClickListener(Context context, String methodName) { 178 mContext = context; 179 Class c = context.getClass(); 180 try { 181 mMethod = c.getMethod(methodName, PARAM_TYPES); 182 } catch (Exception e) { 183 InflateException ex = new InflateException( 184 "Couldn't resolve menu item onClick handler " + methodName + 185 " in class " + c.getName()); 186 ex.initCause(e); 187 throw ex; 188 } 189 } 190 191 public boolean onMenuItemClick(MenuItem item) { 192 try { 193 if (mMethod.getReturnType() == Boolean.TYPE) { 194 return (Boolean) mMethod.invoke(mContext, item); 195 } else { 196 mMethod.invoke(mContext, item); 197 return true; 198 } 199 } catch (Exception e) { 200 throw new RuntimeException(e); 201 } 202 } 203 } 204 205 /** 206 * State for the current menu. 207 * <p> 208 * Groups can not be nested unless there is another menu (which will have 209 * its state class). 210 */ 211 private class MenuState { 212 private Menu menu; 213 214 /* 215 * Group state is set on items as they are added, allowing an item to 216 * override its group state. (As opposed to set on items at the group end tag.) 217 */ 218 private int groupId; 219 private int groupCategory; 220 private int groupOrder; 221 private int groupCheckable; 222 private boolean groupVisible; 223 private boolean groupEnabled; 224 225 private boolean itemAdded; 226 private int itemId; 227 private int itemCategoryOrder; 228 private String itemTitle; 229 private String itemTitleCondensed; 230 private int itemIconResId; 231 private char itemAlphabeticShortcut; 232 private char itemNumericShortcut; 233 /** 234 * Sync to attrs.xml enum: 235 * - 0: none 236 * - 1: all 237 * - 2: exclusive 238 */ 239 private int itemCheckable; 240 private boolean itemChecked; 241 private boolean itemVisible; 242 private boolean itemEnabled; 243 244 private String itemListenerMethodName; 245 246 private static final int defaultGroupId = NO_ID; 247 private static final int defaultItemId = NO_ID; 248 private static final int defaultItemCategory = 0; 249 private static final int defaultItemOrder = 0; 250 private static final int defaultItemCheckable = 0; 251 private static final boolean defaultItemChecked = false; 252 private static final boolean defaultItemVisible = true; 253 private static final boolean defaultItemEnabled = true; 254 255 public MenuState(final Menu menu) { 256 this.menu = menu; 257 258 resetGroup(); 259 } 260 261 public void resetGroup() { 262 groupId = defaultGroupId; 263 groupCategory = defaultItemCategory; 264 groupOrder = defaultItemOrder; 265 groupCheckable = defaultItemCheckable; 266 groupVisible = defaultItemVisible; 267 groupEnabled = defaultItemEnabled; 268 } 269 270 /** 271 * Called when the parser is pointing to a group tag. 272 */ 273 public void readGroup(AttributeSet attrs) { 274 TypedArray a = mContext.obtainStyledAttributes(attrs, 275 com.android.internal.R.styleable.MenuGroup); 276 277 groupId = a.getResourceId(com.android.internal.R.styleable.MenuGroup_id, defaultGroupId); 278 groupCategory = a.getInt(com.android.internal.R.styleable.MenuGroup_menuCategory, defaultItemCategory); 279 groupOrder = a.getInt(com.android.internal.R.styleable.MenuGroup_orderInCategory, defaultItemOrder); 280 groupCheckable = a.getInt(com.android.internal.R.styleable.MenuGroup_checkableBehavior, defaultItemCheckable); 281 groupVisible = a.getBoolean(com.android.internal.R.styleable.MenuGroup_visible, defaultItemVisible); 282 groupEnabled = a.getBoolean(com.android.internal.R.styleable.MenuGroup_enabled, defaultItemEnabled); 283 284 a.recycle(); 285 } 286 287 /** 288 * Called when the parser is pointing to an item tag. 289 */ 290 public void readItem(AttributeSet attrs) { 291 TypedArray a = mContext.obtainStyledAttributes(attrs, 292 com.android.internal.R.styleable.MenuItem); 293 294 // Inherit attributes from the group as default value 295 itemId = a.getResourceId(com.android.internal.R.styleable.MenuItem_id, defaultItemId); 296 final int category = a.getInt(com.android.internal.R.styleable.MenuItem_menuCategory, groupCategory); 297 final int order = a.getInt(com.android.internal.R.styleable.MenuItem_orderInCategory, groupOrder); 298 itemCategoryOrder = (category & Menu.CATEGORY_MASK) | (order & Menu.USER_MASK); 299 itemTitle = a.getString(com.android.internal.R.styleable.MenuItem_title); 300 itemTitleCondensed = a.getString(com.android.internal.R.styleable.MenuItem_titleCondensed); 301 itemIconResId = a.getResourceId(com.android.internal.R.styleable.MenuItem_icon, 0); 302 itemAlphabeticShortcut = 303 getShortcut(a.getString(com.android.internal.R.styleable.MenuItem_alphabeticShortcut)); 304 itemNumericShortcut = 305 getShortcut(a.getString(com.android.internal.R.styleable.MenuItem_numericShortcut)); 306 if (a.hasValue(com.android.internal.R.styleable.MenuItem_checkable)) { 307 // Item has attribute checkable, use it 308 itemCheckable = a.getBoolean(com.android.internal.R.styleable.MenuItem_checkable, false) ? 1 : 0; 309 } else { 310 // Item does not have attribute, use the group's (group can have one more state 311 // for checkable that represents the exclusive checkable) 312 itemCheckable = groupCheckable; 313 } 314 itemChecked = a.getBoolean(com.android.internal.R.styleable.MenuItem_checked, defaultItemChecked); 315 itemVisible = a.getBoolean(com.android.internal.R.styleable.MenuItem_visible, groupVisible); 316 itemEnabled = a.getBoolean(com.android.internal.R.styleable.MenuItem_enabled, groupEnabled); 317 itemListenerMethodName = a.getString(com.android.internal.R.styleable.MenuItem_onClick); 318 319 a.recycle(); 320 321 itemAdded = false; 322 } 323 324 private char getShortcut(String shortcutString) { 325 if (shortcutString == null) { 326 return 0; 327 } else { 328 return shortcutString.charAt(0); 329 } 330 } 331 332 private void setItem(MenuItem item) { 333 item.setChecked(itemChecked) 334 .setVisible(itemVisible) 335 .setEnabled(itemEnabled) 336 .setCheckable(itemCheckable >= 1) 337 .setTitleCondensed(itemTitleCondensed) 338 .setIcon(itemIconResId) 339 .setAlphabeticShortcut(itemAlphabeticShortcut) 340 .setNumericShortcut(itemNumericShortcut); 341 342 if (itemListenerMethodName != null) { 343 item.setOnMenuItemClickListener( 344 new InflatedOnMenuItemClickListener(mContext, itemListenerMethodName)); 345 } 346 347 if (itemCheckable >= 2 && item instanceof MenuItemImpl) { 348 ((MenuItemImpl) item).setExclusiveCheckable(true); 349 } 350 } 351 352 public void addItem() { 353 itemAdded = true; 354 setItem(menu.add(groupId, itemId, itemCategoryOrder, itemTitle)); 355 } 356 357 public SubMenu addSubMenuItem() { 358 itemAdded = true; 359 SubMenu subMenu = menu.addSubMenu(groupId, itemId, itemCategoryOrder, itemTitle); 360 setItem(subMenu.getItem()); 361 return subMenu; 362 } 363 364 public boolean hasAddedItem() { 365 return itemAdded; 366 } 367 } 368 369} 370