[Android] Progamatically Open and Close an Activity’s Option Menu

An Activity‘s option menu can be programatically opened and closed with the openOptionsMenu and closeOptionsMenu respectively. In the example below, a listener is added to a button to open up the options menu. The menu is then closed after a period of time (about 10 seconds).

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

 * Demonstration for programatically opening and closing an {@link Activity}'s
 * option menu.
 * This code should be used as an EXAMPLE ONLY and is provided WITHOUT WARRANTY.
 * @see https://kahdev.wordpress.com/2010/03/15/progamatically-open-and-close-the-activitys-option-menu
 * @author Kah Copyright 2010
public class SimpleShowMenuDemo extends Activity {

	 * Called when the activity is first created.
	public void onCreate(Bundle savedInstanceState) {

		Button menuButton = (Button) findViewById(R.id.menuButton);

		// Display the options menu when the button is clicked.
		menuButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

	 * {@inheritDoc}
	public boolean onCreateOptionsMenu(Menu menu) {


		// Return true so that the menu gets displayed.
		return true;

	 * {@inheritDoc}
	public boolean onPrepareOptionsMenu(Menu menu) {
		// Close the menu after a period of time.
		// Note that this STARTS the timer when the options menu is being
		// prepared, NOT when the menu is made visible.
		Timer timing = new Timer();
		timing.schedule(new TimerTask() {

			 * {@inheritDoc}
			public void run() {
		}, 10000);
		return super.onPrepareOptionsMenu(menu);

The files for this example are downloadable from here.

Similary, the context menu for a view is opened and closed using openContextView and closeContextMenu respectively.

3 Responses to [Android] Progamatically Open and Close an Activity’s Option Menu

  1. Ankit says:

    is there any callback which gets called when option menu gets close?

  2. Very nice tutorial you on option menu can also check this one at

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


Get every new post delivered to your Inbox.

%d bloggers like this: