============================(一)=========================
listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
menu.setHeaderTitle("菜单");
menu.add(0, 0, 0,"添加" );
menu.add(0, 1, 0,"删除");
}
});
============================(二)=========================
registerForContextMenu(lv);
================================================================
1.在activity的onCreate(...)方法中为一个view注册上下文菜单
registerForContextMenu(lv);
2.在onCreateContextMenuInfo(...)中生成上下文菜单。
/*创建上下文菜单*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, 1, 1, "删除");
}
3.在onContextItemSelected(...)中响应上下文菜单项。
/*设置上下文菜单点击事件*/
@Override
public boolean onContextItemSelected(final MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if(item.getItemId()==1){
new AlertDialog.Builder(this) //新建对话框
.setTitle("警告")
.setMessage("确定要删除么?")
.setIcon(R.drawable.plugin_notice) //设置图标
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
db.deleteNote(String.valueOf(info.id)); //删除数据库中该项内容
refreshListView(); //刷新listview
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
return super.onContextItemSelected(item);
}
注:参考