Example goal:
in a displayed content area, touch the screen to display a context menu, and implement listening, when the Zecai item is selected, the content of the item that the user selects. Implementation principle:1, to the content activity needs to display the context menu content Area Registration context Menu Response2. Design context Menu Style3. How to implement context menu in activity Code:the XML content of the context menu
<?xml version= "1.0" encoding= "Utf-8"?>
<menu xmlns:android= "Http://schemas.android.com/apk/res/android" >
<item android:id= "@+id/menu1"
Android:title= "Menu One"
/>
<item android:id= "@+id/menu2"
Android:title= "Menu Two"
/>
</menu>
This section needs to be placed under the Res/menu directorya simple content area (menu departure area)
<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent" >
<textview
Android:id= "@+id/menuview"
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content"
android:text= "Aaaaaaa"/>
</LinearLayout>
for simplicity, just have a label. The most important part of the activity's code, first registering the context menu response in the OnCreate method
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.context_menu);
TextView view = (TextView) Findviewbyid (R.id.menuview);
Registerforcontextmenu (view);
}
we first acquired the TextView area we defined and registered the context menu. ways to implement touch screen response menusOncreatecontextmenu
@Override
public void Oncreatecontextmenu (ContextMenu menu, View V, contextmenu.contextmenuinfo menuinfo) {
Super.oncreatecontextmenu (menu, V, menuinfo);
Menuinflater menuinflater = Getmenuinflater ();
Menuinflater.inflate (R.menu.my_menu, menu);
}
When selecting a menu, a response is required, which is oncontextitemselected
@Override
public boolean oncontextitemselected (MenuItem item) {
Switch (Item.getitemid ()) {
Case R.ID.MENU1:
Toast.maketext (This,
"Select Menu One",
Toast.length_short). Show ();
return true;
Case R.ID.MENU2:
Toast.maketext (This,
"Select Menu Two",
Toast.length_short). Show ();
return true;
Default
return super.oncontextitemselected (item);
}
}
when the menu is selected, the user is prompted to choose which menu to use.
Android Learning notes--Create a simple context menu ContextMenu