Thursday, January 8, 2009

Options Menu in Android (Code)

There are 2 types of menu in Android one is the "options menu" and the other is "context menu".

The options menu is shown when you press the "Menu" button on the device, In this example we would only show how to use codes to display the options.
There are four ways of adding a menu item on your application, but it can be minimized into 2 ways, the following codes would explain these.

package com.monmonja.firstDemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class Main extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.main);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add("Search");
    menu.add(R.string.schedule);
    return super.onCreateOptionsMenu(menu);
  }
}

Quick Explanation
In creating a menu you need to override onCreateOptionsMenu (on Eclipse, right click on your codes then Source, Override/Implement Methods, search for onCreateOptionsMenu). Then inside we call menu.add which takes one parameter either int titleRes or CharSequence title. Here either it takes a string or a resource object.


package com.monmonja.firstDemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class Main extends Activity {
  private int searchBtnId = Menu.FIRST;
  private int scheduleBtnId = Menu.FIRST + 1;
  private int playBtnId = Menu.FIRST + 2;
  private int stopBtnId = Menu.FIRST + 3;
  private int group1Id = 1;
  private int group2Id = 2;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.main);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(group1Id,searchBtnId ,searchBtnId,"Search");
    menu.add(group2Id,scheduleBtnId ,scheduleBtnId,R.string.schedule);
    menu.add(group2Id,playBtnId ,playBtnId,"Play");
    menu.add(group2Id,stopBtnId ,stopBtnId,R.string.stop);
    // the following line will hide search 
    // when we turn the 2nd parameter to false
    menu.setGroupVisible(1, false);
    return super.onCreateOptionsMenu(menu);
  }
}


Quick Explanation
Second menu.add takes 4 parameters, having an int groupId, int itemId, int order, and the four one as either int titleRes or CharSequence title. The first one is a group id, so you can group menu and hide other groups or show other groups. The second one is the menu item id, then the third is the order where you want then to be shown and the last one is the label of the menu item.

References
Common Tasks in Android
Post a Comment