Monday, June 18, 2012

How To Implement Menu Which Uses Check-able Items In Android

                     The project describes How to implement a menu which uses Check-able items.
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:
<menu xmlns: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" />
3.) Define the required strings in strings.xml.

4.) Make sure you write following method in MyCheckBoxMenu class:
public boolean onCreateOptionsMenu(Menu menu)
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(, menu);
    return true;
The inflater.inflate() method loads the menu file for the Activity, specified by the resource ID — refers to the res/menu/menu.xml menu file.
5.) Create and Open res/xml/settings.xml file and insert following code:
<PreferenceScreen xmlns: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" />
This will create a menu which will have checkbox to select and deselect settings for application and will be saved accordingly in prefs.
6.) Next add a new activity in manifest.xml for prefs class.
<activity android:name="org.example.MyCheckBoxMenu.Prefs" 
7.) Run the application.
Steps to Create:
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 Following code must be added in MyCheckBoxMenu class to get the menu work.
public boolean onOptionsItemSelected(MenuItem item)
    switch (item.getItemId())
                startActivity(new Intent(this, Prefs.class));
        return true;
                return true;
  return false;
package org.example.MyCheckBoxMenu;
import org.example.MyCheckBoxMenu.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity {
        protected void onCreate(Bundle savedInstanceState) {
Output –The final output:

No comments:

Post a Comment