<? xml version = "1.0" encoding = "utf-8" ?> < menu xmlns:android = "http://schemas.android.com/apk/res/android" > < item android:id = "@+id/menuItem1" android:icon = "@drawable/menu_item1" android:title = "@string/menu_item1" /> < item android:id = "@+id/menuItem2" android:icon = "@drawable/menu_item2" android:title = "@string/menu_item2" /> </ menu > |
<? xml version = "1.0" encoding = "utf-8" ?> < resources > < string name = "hello" >Hello World, AndroidMenus!</ string > < string name = "app_name" >Android Menus</ string > < string name = "menu_item1" >Item 1</ string > < string name = "menu_item2" >Item 2</ string > </ resources > |
package com.giantflyingsaucer; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; public class AndroidMenus extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.mymenu, menu); return true ; } } |
Once you’ve got this done you can run the project. In the emulator press the “Menu” button to trigger the menu.
Results:
Yes its pretty ugly but like I said I’m not a graphics person. If you click on the menu items nothing happens, lets change this now by adding some Java code to the “AndroidMenus.java” file. For this we need to override the onOptionsItemSelected method.
package com.giantflyingsaucer; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; public class AndroidMenus extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.mymenu, menu); return true ; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menuItem1: Toast.makeText(AndroidMenus. this , "Menu Item 1 was pressed" , 3000 ).show(); return true ; case R.id.menuItem2: Toast.makeText(AndroidMenus. this , "Menu Item 2 was pressed" , 3000 ).show(); return true ; default : return super .onOptionsItemSelected(item); } } } |
Results:
Full download