Android @ Kiowok

Options Menus

To setup a options menu for an activity, write the XML to describe the menu, in res/menu. You might need to create the menu folder. Menus are specific to a given activity, and the menu's XML filename often mirrors the name of the activity that the menu is attached to. Here is a sample main_activity.xml file:

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/item_makeup_an_id" android:title="Makeup some Name" />

</menu>

In the activity's Java code, add the following methods:

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		this.getMenuInflater().inflate(R.menu.main_activity, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.makeup_an_id:
			// Do useful things here...

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

Enabling and Disabling Options Menu Items

To enable or disable a specific menu item -- below we're looking at an item on the menu with the id of item_demo:

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
	    MenuItem itemDemo = menu.findItem(R.id.item_demo);

	    if (some condition is true) {
	    	itemDemo.setEnabled(true);
	    }
	    else {
	    	itemDemo.setEnabled(false);
	    }
	    
	    return super.onPrepareOptionsMenu(menu);
	}

Context Menus

A typical way of bringing up a context menu for an Android widget is to long click the widget.

Here we'll look at adding a context menu for a ListView, with an id of listView.

Setup the XML to Describe the Context Menu

Create a file named main_activity_list_context.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item_1" android:title="Item 1" />
</menu>

Register the Context Menu

Add the following code (such as in onCreate):

        registerForContextMenu(listView);
    

Add the Code to Display the Context Menu and Handle Menu Events

    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    	getMenuInflater().inflate(R.menu.main_activity_list_context, menu);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	int position = info.position;
    	Something selectedItem = adapter.getItem(position);  // Adapter was declared as: ArrayAdapter<Something> adapter;
    	
    	switch (item.getItemId()) {
    	case R.id.item_1:
    		// Manipulate or query the selected item.  If changes were made, then notify the adapter:
    		adapter.notifyDataSetChanged();
    		return true;
    	}
    	return super.onContextItemSelected(item);
    }
    
Top