0

我想从触发上下文菜单的项目中获取列表中的位置。这是我的代码:

@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 才能正确执行。

非常感谢!

4

1 回答 1

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;

}
于 2013-01-18T04:56:38.367 回答