RSS

Simple Options Menu in Android

23 Jan
  1. Create an Android XML file of Menu type
  2. Add menu options as you preferred. Each menu option should be indicated as <item> XML element.
  3. This is my options.xml file.
    <!--?xml version=<em--><?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <item android:id="@+id/item1" android:title="Edit" android:icon="@android:drawable/ic_menu_edit"></item>
    <item android:id="@+id/item2" android:title="Delete" android:icon="@android:drawable/ic_menu_delete"></item>
    <item android:id="@+id/item3" android:title="Help" android:icon="@android:drawable/ic_menu_help"></item>
    <item android:id="@+id/item4" android:title="More" android:icon="@android:drawable/ic_menu_more"></item>
    
    
    </menu>
    
  4. My options menu is not just text-based. Each menu item is displayed with a relevant icon. Here I used the icons found in the Android.jar file of my project. You can find such icons using this path
    <app root > –> Android <Your Android platform>  –> android.jar –> res –> drawable-hdpi(icons for menu prefixed with ic_menu)
  5. Override onCreateOptionsMenu and onOptionsItemSelected in your Activity.java file
    package com.my.option;
    
    import java.io.Console;
    import java.util.zip.Inflater;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    
    public class OptionMenuActivity 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 inflator = getMenuInflater();
    inflator.inflate(R.menu.options, menu);
    return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.item1)
    Log.d("Edit", "Selected : Edit Option");
    if(item.getItemId() == R.id.item2)
    Log.d("Delete", "Selected : Delete Option");
    return super.onOptionsItemSelected(item);
    }
    }
    
Advertisements
 
Leave a comment

Posted by on January 23, 2012 in Android

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: