Options Menu in Android Development

12

The project describes How to implement option menu into your application. Option menu is the primary collection of menu items for an activity, which appears when the user touches the MENU button.

Underlying Algorithm:

Basic description of algorithm in step by step form:

  1. Create a Project MyCheckBoxMenu
  2. Create and Open the res/menu/menu.xml file and insert the following:
  3. <menu xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:id="@+id/settings_title"
              android:title="@string/settings_title" />
      <item android:id="@+id/back_title"
              android:title="@string/back_title" />
      <item android:id="@+id/exit_title"
              android:title="@string/exit_title" />
    </menu>
    
  4. Define the required strings in strings.xml.
  5. Make sure you write following method in MyCheckBoxMenu class:
  6. public boolean onCreateOptionsMenu(Menu menu)
    {
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
    }
    

    The inflater.inflate() method loads the menu file for the Activity, specified by the resource ID — R.menu.menu refers to the res/menu/menu.xml menu file.

  7. Create and Open res/xml/settings.xml file and insert following code:
  8. <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference android:key="music"
    android:title="@string/music_title" android:summary="@string/music_summary"
    		android:defaultValue="true" />
    	<CheckBoxPreference android:key="hints"
    android:title="@string/hints_title" android:summary="@string/hints_summary"
    		android:defaultValue="true" />
    </PreferenceScreen>
    

    This will create a menu which will have checkbox to select and deselect settings for application and will be saved accordingly in prefs.

  9. Next add a new activity in manifest.xml for prefs class.
  10. <activity android:name="org.example.MyCheckBoxMenu.Prefs" 
    		android:label="@string/settings_title">
    	</activity>
    
  11. Run the application.

Steps to Create New Project:

  1. Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. MyCheckBoxMenu
  2. Then enter the following information:
  • Project name: MyCheckBoxMenu
  • Build Target: Android 1.6
  • Application name: MyCheckBoxMenu
  • Package name: org.example.MyCheckBoxMenu
  • Create Activity: MyCheckBoxMenu

On Clicking Finish MyCheckBoxMenu code structure is generated with the necessary Android Packages being imported along with MyCheckBoxMenu.java. Following code must be added in MyCheckBoxMenu class to get the menu work.

public boolean onOptionsItemSelected(MenuItem item) 
{
    switch (item.getItemId()) 
    {
    	case R.id.settings_title:
    		startActivity(new Intent(this, Prefs.class));
    	return true;
case R.id.exit_title:
    		finish();
    		return true;
    }
  return false;
}

Prefs.java

package org.example.MyCheckBoxMenu;
import org.example.MyCheckBoxMenu.R;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class Prefs extends PreferenceActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);
	}
}

Output –The final output:

Click on “MENU”

Click on “Options”

Did you enjoy this article?
Share
the
Love
Get Free Updates

12 Responses

  1. Thanks for the great content, Very informative.

  2. Dilshan says:

    Nice tutorial
    Thanks

  3. Amit Suri says:

    Another nice tutorial, could you please send me source code for the same my email id is:- android.amitsuri@gmail.com

  4. yalini says:

    Hi this is very useful. Thanks alot

  5. Alex says:

    Come on…, this is , I could say “deprecated” since the menu button is no use starting with Android 4.0.3. You would better write a tutorial about how to use the action bar and new Menu features starting with Android 4 and above. I disagree with this tutorial. Thank you!
    Regards,
    Alex

  6. Ganesh says:

    nice ..its very impressive for me..
    Can you post any application related to multiple tab and how to open app in saperate tab

  7. RalF says:

    Thank you very much. This helped me a lot creating an options menu for my Android 2.3 App!

  8. darshan says:

    good examples

  9. Shubho says:

    I have done the things as mentioned above. But not getting the menus exactly in my activity. When i press the menu button, three white boxes are created but no item names are shown neither code under the item(case) is executing on clicking those blank menu boxes.

    my code is

    1.menu.xml

    the activity where i want to use menu

    2. Strings.xml

    User name
    Password
    Tet Guru
    Home
    Exit
    Logout

    3.TakeAtestActivity.java

    package com.tetguru.android;

    import android.app.Activity;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;

    public class TakeATestActivity extends Activity{

    Button btnLowTest, btnMediumTest, btnHighTest;
    TextView tvPaperHeading, tvChooseDifficulty;

    public void onCreate(Bundle b){
    super.onCreate(b);
    setContentView(R.layout.taketest);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    SharedPreferences.Editor editor = prefs.edit();

    int examTaken = prefs.getInt(“pref_examTaken”, 0);
    int maxExamLimit = prefs.getInt(“pref_maxExamLimit”, 0);
    int moduleId = prefs.getInt(“pref_moduleId”, 0);
    String paper=””;
    if(moduleId ==4)
    paper=”PAPER 1″;
    else
    paper=”PAPER 2″;
    // put the paper value in the shared preference
    editor.putString(“perf_paper”, paper);
    editor.commit();
    tvPaperHeading = (TextView)findViewById(R.id.taketest_tv_para1);
    tvPaperHeading.setText(“SPEED TEST [“+(examTaken+1)+”/”+maxExamLimit+”] (“+paper+”)”);

    tvChooseDifficulty = (TextView)findViewById(R.id.taketest_tv_para2);
    tvChooseDifficulty.setText(“Choose Difficulty Level”);

    addListenerOnbtnLowTest();
    addListenerOnbtnMediumTest();
    addListenerOnbtnHighTest();

    }

    public void addListenerOnbtnLowTest(){
    btnLowTest = (Button)findViewById(R.id.takeAtest_btnLow);
    btnLowTest.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent intent = new Intent(TakeATestActivity.this, BeforeTestActivity.class);
    intent.putExtra(“imgRsc”, “l”);
    startActivity(intent);
    finish();
    }

    });
    }

    public void addListenerOnbtnMediumTest(){
    btnMediumTest = (Button)findViewById(R.id.takeAtest_btnMedium);
    btnMediumTest.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent intent = new Intent(TakeATestActivity.this, BeforeTestActivity.class);
    intent.putExtra(“imgRsc”, “m”);
    startActivity(intent);
    finish();
    }

    });

    }
    /**
    *
    */
    public void addListenerOnbtnHighTest(){
    btnHighTest = (Button)findViewById(R.id.takeAtest_btnHigh);
    btnHighTest.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent intent = new Intent(TakeATestActivity.this, BeforeTestActivity.class);
    intent.putExtra(“imgRsc”, “h”);
    startActivity(intent);
    finish();
    }

    });

    }
    /**
    * Create the menu in this activity when menu buton of the device is clicked
    */
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.layout.menu, menu);
    return true;

    }

    /**
    * corresponding action is taken depending on which item is clicked
    */
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    Intent i;
    switch(item.getItemId()){
    case R.id.menu_home:
    i = new Intent(TakeATestActivity.this,HomeActivity.class);
    startActivity(i);
    return true;
    case R.id.menu_logout:
    i = new Intent(TakeATestActivity.this,LoginActivity.class);
    startActivity(i);
    return true;
    case R.id.menu_exit:
    finish();
    return true;
    default:
    return false;
    }
    }
    }

  10. Howdy! This blog post could not be written much better!Reading through this article reminds me of my previous roommate!He always kept preaching about this. I will send thispost to him. Pretty sure he’ll have a very good read. Many thanks for sharing!

  11. Adrail says:

    Hello. Can you send to me please the project? because i have errors in that) If You can)
    thanks You
    adrail@mail.com

  12. bleuman says:

    Very usefull,
    Thank you very much

Leave a Reply


+ three = 8

Proudly designed by Theme Junkie.