Android Menu Design (2): Options Menu precautions

Source: Internet
Author: User

In Android Menu Design (1): the Options menu is created using the XML file layout. But in actual development, you still need to pay attention to several issues. This article discusses related issues.

Before entering the formal topic, you need to know something.

1. Create option menus using XML

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android">    <item android:id="@+id/new_game"          android:icon="@drawable/ic_new_game"          android:title="@string/new_game" />    <item android:id="@+id/help"          android:icon="@drawable/ic_help"          android:title="@string/help" /></menu>

Note: When using menu. in the getitem (INT index) method, the index parameter is the order in which you create items in XML. For example, the menu with ID new_game above is the option with Index = 0, the menu with ID help is the option with Index = 1.

This method declaration:

MenuItem android.view.Menu.getItem(int index)Gets the menu item at the given index.Parameters:    index The index of the menu item to return.Returns:    The menu item.Throws:    IndexOutOfBoundsException - when index < 0 || >= size()

2. Menu XML attributes

Here, only one attribute is used. Android: enabled = ["true" | "false"] corresponds to seteable (Boolean ). This attribute is used to set whether a menu is available. As shown in, the left side is unavailable and the right side is available.

For more detailed documentation, go to SDK-path/doc/dev Guide/framework topics/application resources/resource types/menu.

OK. Go back to the topic.

3. project directory structure

4. Activity Code

Package mark. zhang; import android. app. activity; import android. OS. bundle; import android. util. log; import android. view. layoutinflater; import android. view. menu; import android. view. menuinflater; import android. view. menuitem; import android. view. view; import android. view. view. onclicklistener; import android. widget. edittext; public class testmenuenableactivity extends activity {private menuitem item_clearall = NULL; private edittext showinfo = NULL; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); showinfo = (edittext) findviewbyid (R. id. testmenu_edit); item_clearall = (menuitem) findviewbyid (R. id. menu_clearall); findviewbyid (R. id. testmenu_button ). setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {I F (item_clearall! = NULL) {item_clearall.setenabled (true); showinfo. settext ("It enables item_clearall successfully! ");} Else {showinfo. settext (" item_clearall is null, it do not enable item_clearall! ") ;}}) ;}@ Overridepublic Boolean oncreateoptionsmenu (menu) {menuinflater Inflater = getmenuinflater (); Inflater. inflate (R. menu. ui_optionsmenu, menu); // item_clearall = (menuitem) findviewbyid (R. id. menu_clearall); // item_clearall = menu. getitem (0); return Super. oncreateoptionsmenu (menu) ;}@ overridepublic Boolean onoptionsitemselected (menuitem item) {Switch (item. getitemid () {case R. id. menu_clearall: // clear all logs. D ("mark", "clearall"); Return true; case R. id. menu_help: // help log. D ("mark", "help"); Return true; case R. id. menu_exit: Finish (); Return true; default: return Super. onoptionsitemselected (item );}}}

5. xml file of menu

<? XML version = "1.0" encoding = "UTF-8"?> <Menu xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Id = "@ + ID/mymenu"> <item Android: Id = "@ + ID/menu_clearall" Android: title = "Clear all records" Android: enabled = "false"/> <item Android: Id = "@ + ID/menu_help" Android: title = "help"/> <item Android: Id = "@ + ID/menu_exit" Android: Title = "quit"/> </menu>

Note: The menu with ID menu_clearall is unavailable here. In the activity code (click the button event) to restore it to availability.

Run the application on the following page:

Click test menu to display the result:

The findviewbyid method cannot be used to obtain the menuitem object. Then, I will code:

item_ClearAll = (MenuItem) findViewById(R.id.menu_clearAll);

Put it in the callback method oncreateoptionsmenu and modify it as follows:

@Overridepublic boolean onCreateOptionsMenu(Menu menu) {MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.ui_optionsmenu, menu);item_ClearAll = (MenuItem) findViewById(R.id.menu_clearAll);//item_ClearAll = menu.getItem(0);return super.onCreateOptionsMenu(menu);}

Run the command again. First, click the menu button on the mobile phone, and make sure that the oncreateoptionsmenu is called back to execute item_clearall = (menuitem) findviewbyid (R. Id. menu_clearall). The effect is as follows:

Then, click test menu to create a menuitem object. Khan!

Modify the callback Method Code as follows:

@Overridepublic boolean onCreateOptionsMenu(Menu menu) {MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.ui_optionsmenu, menu);//item_ClearAll = (MenuItem) findViewById(R.id.menu_clearAll);item_ClearAll = menu.getItem(0);return super.onCreateOptionsMenu(menu);}

We can see that the getitem method is used to create a menuitem object. Of course, you need to first click the menu button, then click test menu, and then click the menu button again to achieve the following effect.

The menuitem object is successfully created and the menu is enabled.

6. Thinking

Use the inflate method of layoutinflater to try it?

LayoutInflater inflater = LayoutInflater.from(this);View view = inflater.inflate(R.menu.ui_optionsmenu, null);item_ClearAll = (MenuItem)view.findViewById(R.id.menu_clearAll);

Put the above Code in the callback method oncreateoptionsmenu or elsewhere. After running the code, an exception is reported:

08-15 06:29:48.195: ERROR/AndroidRuntime(876): Caused by: java.lang.ClassNotFoundException: android.view.menu in loader dalvik.system.PathClassLoader@44c1770008-15 06:29:48.195: ERROR/AndroidRuntime(876):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)08-15 06:29:48.195: ERROR/AndroidRuntime(876):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)08-15 06:29:48.195: ERROR/AndroidRuntime(876):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)08-15 06:29:48.195: ERROR/AndroidRuntime(876):     at android.view.LayoutInflater.createView(LayoutInflater.java:466)08-15 06:29:48.195: ERROR/AndroidRuntime(876):     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:544)08-15 06:29:48.195: ERROR/AndroidRuntime(876):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66)08-15 06:29:48.195: ERROR/AndroidRuntime(876):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)

Finally, I studied the source code:

public View inflate(int resource, ViewGroup root, boolean attachToRoot) {        if (DEBUG) System.out.println("INFLATING from resource: " + resource);        XmlResourceParser parser = getContext().getResources().getLayout(resource);        try {            return inflate(parser, root, attachToRoot);        } finally {            parser.close();        }    }

It can be seen that this method is generally used to parse the resource files under the layout folder. Menu is a folder under Res and does not belong to layout. If you observe it, in the callback method oncreateoptionsmenu, use:

MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.ui_optionsmenu, menu);

To instantiate the menu folder. Source code of the inflate method:

 public void inflate(int menuRes, Menu menu) {        XmlResourceParser parser = null;        try {            parser = mContext.getResources().getLayout(menuRes);            AttributeSet attrs = Xml.asAttributeSet(parser);                        parseMenu(parser, attrs, menu);        } catch (XmlPullParserException e) {            throw new InflateException("Error inflating menu XML", e);        } catch (IOException e) {            throw new InflateException("Error inflating menu XML", e);        } finally {            if (parser != null) parser.close();        }    }

About menu, we recommend an article: http://www.cnblogs.com/xirihanlin/archive/2010/06/25/1765261.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.