1,在onCreate方法中加:
// 长按启动上下文菜单
getListView().setOnCreateContextMenuListener(this);
2,设置上下文菜单中有什么菜单:
// 启动上下文菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
if (cursor1 == null)
return;
// 设置了上下文菜单的标题为点击的item的值ֵ
menu.setHeaderTitle(R.string._index_menu_title);
menu.setHeaderIcon(R.drawable.folder_open_delete);
// 设置上下文菜单的选项
menu.add(0, 1, 0, R.string._index_menu_item1);
menu.add(0, 2, 0, R.string._index_menu_item2);
super.onCreateContextMenu(menu, v, menuInfo);
}
3,菜单项对应的操作:
// 上下文菜单回调函数
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo acmenuinfo = (AdapterContextMenuInfo) item
.getMenuInfo();
int post = (int) getListAdapter().getItemId(acmenuinfo.position);// 取到id号(这个id为数据库中的对应id)
switch (item.getItemId()) {
case 1:
// 根据id删除这一行
try {
imageDbhelp1.delete(post);
onCreate(null); // refresh phone screen
Toast.makeText(Index.this, "delete successful",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO: handle exception
Log.e("Exception", e.getMessage(), e);
}
break;
}
return super.onContextItemSelected(item);
}