步骤如下,代码不完全
1、 calling registerForContextMenu()
//给listview注册上下文菜单
registerForContextMenu(lv_call_sms_safe);
2、calls your onCreateContextMenu() method
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);//这段代码把资源文件中的menu的配置转化为对象
}
3、context_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/update_number" android:title="更改"></item>
<item android:id="@+id/delete_number" android:title="删除"></item>
</menu>
4、Implement onContextItemSelected()
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int id=(int) info.id;
String number=numbers.get(id);
switch (item.getItemId()) {
case R.id.update_number://更新条目的操作
updatenumber(number);
break;
case R.id.delete_number:
//获取当前条目的id
dao.delete(number);//从数据库中删除
// 重新获取号码
numbers=dao.getAllNumber();
adapter.notifyDataSetChanged();
break;
}
return false;
}