In the previous section, we have learned how to display the option MENU when pressing the MENU key. However, in addition to the option menu, you can also display a context menu. Context menus are usually associated with components in the activity. When you press a component for a long time, its context menu is triggered. For example, if you press a Button long, a context menu may be displayed.
To associate a component with a context menu, call setOnCreateContextMenuListener () on the component ().
The following shows how to display a Context Menu ).
1. Use the previous project to modify main. xml.
[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: orientation = "vertical">
<TextView
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/hello"/>
<Button
Android: id = "@ + id/button1"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
Android: text = "Click and hold on it"/>
</LinearLayout>
2. Add some code in MenusActivity. java.
[Java]
Public class MenusActivity extends Activity {
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Button btn = (Button) findViewById (R. id. button1 );
Btn. setOnCreateContextMenuListener (this );
}
@ Override
Public void onCreateContextMenu (ContextMenu menu, View view,
ContextMenuInfo menuInfo)
{
Super. onCreateContextMenu (menu, view, menuInfo );
CreateMenu (menu );
}
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
......
}
@ Override
Public boolean onOptionsItemSelected (MenuItem item)
{
Return MenuChoice (item );
}
Private void CreateMenu (Menu menu)
{
......
}
Private boolean MenuChoice (MenuItem item)
{
......
}
}
3. Press F11 to debug the simulator. After clicking the Button for a period of time, the context menu is displayed.
In the preceding example, we call the setOnCreateContextMenuListener () method of the button, which is associated with the context menu.
When an item is clicked in the context menu, the onContextItemSelected () method is triggered.
Note that the shortcut keys in the context menu do not work. To enable the shortcut key to work, call the setQuertyMode () method.
[Java]
Private void CreateMenu (Menu menu)
{
Menu. setQwertyMode (true );
MenuItem mnu1 = menu. add (0, 0, 0, "Item 1 ");
{
Mnu1.setAlphabeticShortcut ('A ');
Mnu1.setIcon (R. drawable. ic_launcher );
}
......
}