How to create a pop-up menu in Android development:
1. First give the View Register context menu Registerforcontextmenu ();
2. Add context menu Content Oncreatecontextmenu ():
---can be added dynamically through code;
---can load menu items in the XML file;
3. Set Menu click Response Event oncontextitemselected ();
Run as follows:
The Activity_main.xml code is as follows:
<relativelayout
Android:layout_width= "Match_parent"
...... omitted here
>
<listview
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
Android:id= "@+id/listview"
/>
</RelativeLayout>
The Mainactivity.java code is as follows:
...... omitted here
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Showlistview ();
}
/**
* Set the display of the ListView
*/
private void Showlistview () {
ListView ListView = Findviewbyid (R.id.listview);
arrayadapter<string> adapter = new Arrayadapter<string> (this,android. R.layout.simple_list_item_1,getdata ());
Listview.setadapter (adapter);
This.registerforcontextmenu (listview);
}
@Override
public void Oncreatecontextmenu (ContextMenu menu,view v,contextmenuinfo menuinfo) {
Super.oncreatecontextmenu (Menu,v,menuinfo);
Set Menu Display content
Menu.setheadertitle ("file operation");
Menu.setheadericon (R.drawable.ic_launcher);
Menu.add (1,1,1, "copy");
Menu.add (1,2,1, "paste");
Menu.add (1,3,1, "cut");
Menu.add (1,4,1, "renaming");
}
@Override
public boolean oncontextitemselected (MenuItem item) {
Switch (Item.getitemid ()) {
Case 1:
Toast.maketext (Mainactivity.this, "click Copy", Toast.length_short). Show ();
Break
Case 2:
Toast.maketext (Mainactivity.this, "Click to paste", Toast.length_short). Show ();
Break
Case 3:
Toast.maketext (Mainactivity.this, "Click Cut", Toast.length_short). Show ();
Break
Case 4:
Toast.maketext (Mainactivity.this, "Click Rename", Toast.length_short). Show ();
Break
}
return super.oncontextitemselected (item);
}
/**
* Construct the data displayed by the ListView
*/
Private Arraylist<string> GetData () {
arraylist<string> list = new arraylist<string> ();
for (int i=0;i<5;i++) {
List.add ("File" + (i+1));
}
return list;
}
Android Developer Long Press Menu context menu