Home > Android, Android how to, Menu > Handling Options Menu item selections in Android

Handling Options Menu item selections in Android


We moved. Please visit this link for this post.

 

 

 

I showed previously how to create an Options menu and how to add Menu item to it.

Now I am going to show how to handle options menu item selection.

I will show code snippet and after whole example.

For this handling need to override onOptionsItemSelected(MenuItem item) method in your Activity:

@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case OK_MENU_ITEM:
			showMsg("Ok");
			break;
		}
		return super.onOptionsItemSelected(item);
	}

And whole example:

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

/**
 * Class which shows how to handle menu item selection
 *
 * @author FaYna Soft Labs
 */
public class Main extends Activity {
	private static final int OK_MENU_ITEM = Menu.FIRST;
	private static final int SAVE_MENU_ITEM = OK_MENU_ITEM + 1;
	private static final int BACK_MENU_ITEM = SAVE_MENU_ITEM + 1;

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, OK_MENU_ITEM, 0, "Ok");
		menu.add(0, SAVE_MENU_ITEM, 0, "Save");
		menu.add(0, BACK_MENU_ITEM, 0, "Back");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case OK_MENU_ITEM:
			showMsg("Ok");
			break;
		case SAVE_MENU_ITEM:
			showMsg("Save");
			break;
		case BACK_MENU_ITEM:
			showMsg("Back");
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void showMsg(String msg) {
		Toast toast = Toast.makeText(Main.this, msg, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, toast.getXOffset() / 2, toast.getYOffset() / 2);
		toast.show();
	}

}

As you see it is very easy to handle menu item selections.

About these ads
Categories: Android, Android how to, Menu
  1. No comments yet.
  1. No trackbacks yet.

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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: