我需要onContextItemSelected()
. 我使用以下代码:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (v.getId()==R.id.listView1) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle("Optionen");
menu.add(Menu.NONE, info.position, 0, "Artikel entfernen");
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final ListView lv = (ListView)findViewById(R.id.listView1);
Toast.makeText(getApplicationContext(), lv.getItemAtPosition(item.getItemId()).toString(), Toast.LENGTH_LONG).show();
return true;
}
info.position
无法从withonContextItemSelected
读取var item.getItemId
!该应用程序崩溃并显示日志:String empty。你能找出错误吗?谢谢!
更新 我将代码更改为:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.listView1) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle("Optionen");
menu.add(Menu.NONE, info.position, 0, "delete post");
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final ListView lv = (ListView)findViewById(R.id.listView1);
//lv.getItemAtPosition(0).toString()
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
Toast.makeText(getApplicationContext(), info.position, Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), lv.getItemAtPosition(item.getItemId()).toString(), Toast.LENGTH_LONG).show();
return true;
}
但是这段代码也不起作用(NotFoundException)。我有一个包含项目的列表视图(R.id.listView1)。如果用户长时间单击某个项目,则会出现上下文菜单。有“删除帖子”选项。然后我需要帖子中的ID来删除它!
还有其他解决方案吗?
更新 2 我解决了这个问题:
Toast.makeText(getApplicationContext(), lv.getItemAtPosition(info.position).toString(), Toast.LENGTH_LONG).show();