步骤
1、重写Activity中的
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
}
ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
}
创建Activity下方的menu菜单
2、创建上下文的Menu
(1)重写
private ListView myListView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myListView = (ListView) findViewById(R.id.myListView);
....
registerForContextMenu(myListView);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myListView = (ListView) findViewById(R.id.myListView);
....
registerForContextMenu(myListView);
}
用registerForContextMenu注册,当常按ListView中的某一项时会弹出Menu
(2)重写
//创建上下文Menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select to do item");
menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select to do item");
menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove);
}
实现点击后弹出的Menu的内容
(3)重写onOptionsItemSelected(MenuItem item)实现活动菜单选中后的操作
//活动菜单选中后的操作
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
int index = myListView.getSelectedItemPosition();
switch (item.getItemId()) {
case (REMOVE_TODO):
if (addingNew) {
cancelAdd();
} else {
removeItem(index);
}
return true;
case (ADD_NEW_TODO):
addNewItem();
return true;
}
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
int index = myListView.getSelectedItemPosition();
switch (item.getItemId()) {
case (REMOVE_TODO):
if (addingNew) {
cancelAdd();
} else {
removeItem(index);
}
return true;
case (ADD_NEW_TODO):
addNewItem();
return true;
}
return false;
}
(4)重写public boolean onContextItemSelected(MenuItem item)实现上下文菜单选中后的操作
//上下文菜单选中后的操作
@Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
switch (item.getItemId()) {
case REMOVE_TODO:
AdapterView.AdapterContextMenuInfo menuInfo;
menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int index = menuInfo.position;
removeItem(index);
return true;
}
return false;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
switch (item.getItemId()) {
case REMOVE_TODO:
AdapterView.AdapterContextMenuInfo menuInfo;
menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int index = menuInfo.position;
removeItem(index);
return true;
}
return false;
}