Sunday, January 5, 2014
How to Create a Menu Step
1. Open your Android project in your Integrated Development Environment. You can locate the menu resources for your application by browsing to the 'res' folder. If you are using Eclipse, which is the recommended IDE for Android, you can access your application directories using the Package Explorer. The menu resources should be placed in a folder named 'menu' inside the 'res' folder. If your application does not yet have a menu folder, create one by right-clicking on the 'res' folder and choosing 'New' then 'Folder.' Enter the name 'menu,' and click 'Finish' in the dialog that appears. Your menu folder should now appear in your application package.
2. Create an XML file for your menu. Right-click your menu folder, and choose 'New,' then 'File' to create an XML file. Enter the name of your file -- for example, 'my_menu.xml' or a name that reflects the purpose of your menu. Your IDE may output error messages because the content of your menu is not correctly structured yet. Ignore these messages for now. Open the XML file in the text editor of your IDE by double-clicking it in the application directory. You should see your menu XML displayed.
3. Alter the XML markup for your menu. Inside your menu file, replace the content with the following outline code:
Save your file. Your IDE should stop outputting error messages. This is the outline of a menu in an Android application. Between the opening and closing menu tags, you can place the items you want your menu to present to your users.
4. Add items to your menu. Between the menu tags in your XML code, add the following sample code to create two menu items for your application:
This code determines the text that will appear for each of your menu items. If you want to add icons, you can store them in your application's 'drawable' folder, altering your XML code as follows:
Alter the code to match the name of your icon image files.
5. Instruct Java to create your menu. In the Java class file for the Activity you want your menu to appear in, you need to instruct the application to display the menu items you defined in your XML code. Open the Java file for the Activity and add the following method:
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.my_menu, menu);
return true;
}This code instructs the application to use the menu outlined in the 'my_menu' XML file.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment