To create a menu using a layout file: (Multilevel menu)
Create a folder under Res menu (if you already have it, you don't have to create it anymore)
Create an XML file under the menu folder here I name the File menu
The menu that was created. In the XML file
Write:
<?xml version= "1.0" encoding= "Utf-8"?>
<menu xmlns:android= "Http://schemas.android.com/apk/res/android" >
<item
Android:id= "@+id/file"
android:title= "File"/>
<item
Android:id= "@+id/edit"
android:title= "Edit"/>
<item
Android:id= "@+id/help"
Android:title= "Help" >
<menu>
<item
Android:id= "@+id/window"
android:title= "Window"/>
<item
Android:id= "@+id/run"
android:title= "Run"/>
</menu>
</item>
</menu>
To create a menu in activity, replace the following code with This.getmenuinflater (). Inflate (R.menu.menu,menu);
R.menu.menu represents the menu XML file you created
Menu.add ("file");
Menu.add ("edit");
Menu.add ("source");
That
Public class Mainactivity extends Activity {
private TextView Username,password;
@Override
protected void OnCreate (Bundle savedinstancestate) {
//TODO auto-generated method stub
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
username = (TextView) Findviewbyid (r.id.username);
password = (TextView) Findviewbyid (R.id.password);
This.registerforcontextmenu (username);//Register Menu
}
@Override
Public void Oncreatecontextmenu (ContextMenu menu, View V,
contextmenuinfo Menuinfo) {
//TODO auto-generated method stub
this.getmenuinflater (). Inflate (R.menu.menu,menu);
Super.oncreatecontextmenu (menu, V, menuinfo);
}
@Override
Public Boolean oncontextitemselected (MenuItem item) {
//TODO auto-generated method stub
execute when Menu context element is selected
Toast.maketext (this, item.gettitle () + "oncontextitemselected", 1). Show ();
return super.oncontextitemselected (item);
}
@Override
Public boolean onmenuitemselected (int featureid, MenuItem item) {
//TODO auto-generated method stub
//Menu element is selected when executed
Toast.maketext (this, item.gettitle () + "onmenuitemselected", 1). Show ();
return super.onmenuitemselected (Featureid, item);
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Popup Multilevel Menu