我想从触发上下文菜单的项目中获取列表中的位置。这是我的代码:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
c = contacts.get(position);
Toast.makeText(v.getContext(), c.getName().toString() + " Clicked " + (id + 1), Toast.LENGTH_SHORT).show();
Intent i = new Intent(v.getContext(), DetailActivity.class);
i.putExtra("key", id + 1);
startActivity(i);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
this.selectedPerson = contacts.get(info.position);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_context, menu);
menu.setHeaderIcon(R.drawable.settings2);
menu.setHeaderTitle(this.selectedPerson.getName().toString() + " - Options");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_edit:
Toast.makeText(this, "Edit", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_delete:
Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_fav:
Toast.makeText(this, "Added to Favourites!", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
我如何以与onListItemClick()
中的方式类似的方式检索位置?原因是,我想调用我的数据库适配器删除方法,它需要行ID才能正确执行。
非常感谢!
答案 0 :(得分:0)
你可以使用
AdapterView.AdapterContextMenuInfo info = AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
onContextItemSelected(MenuItem item)以获取列表适配器的项目位置
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch(item.getItemId()){
case R.id.menu_edit:
Toast.makeText(this, "Edit", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_delete:
Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_fav:
Toast.makeText(this, "Added to Favourites!", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}