如何从上下文菜单中获取文本?

时间:2010-08-22 13:55:32

标签: android

我有一个带有名单列表的ListActivity(Jacob,Will,Matt等)。我有一个contextMenu,它为用户提供了编辑或删除此人的选项。我知道如何找到执行编辑和删除功能的ID,但是我无法弄清楚如何将人的名字添加到意图附加内容中,或者在删除时添加toast。

以下是我用于上下文菜单的代码片段:


@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    switch(item.getItemId()) {
    case DELETE_ID:
        mDbHelper.deletePerson(info.id);
        fillData();
        return true;
    case EDIT_ID:
        Cursor c = mCursor;
        c.moveToPosition(info.position);
        Intent i = new Intent(this, PersonEdit.class);
        i.putExtra("_id", info.id);
        startActivityForResult(i, ACTIVITY_EDIT);
        return true;
    }
    return super.onContextItemSelected(item);
}

2 个答案:

答案 0 :(得分:0)

从我的代码中复制粘贴:

AdapterView.AdapterContextMenuInfo info;

try {
    info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
    Log.e(TAG, "bad menuInfo", e);
    // Do something here.
}

Person person = (Person) getListAdapter().getItem(info.position);

getListAdapter()适用于从ListActivity延伸的活动。如果您不使用它,请获取ListView,然后获取适配器。

答案 1 :(得分:0)

谢谢Macarse。我不知何故偶然发现了自己问题的答案。它似乎工作正常。


@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    Cursor c = mCursor;
    c.moveToPosition(info.position);
    Long id = info.id;
    String person = mCursor.getString(c.getColumnIndexOrThrow("person"));

    switch(item.getItemId()) {
    case DELETE_ID:
        Toast.makeText(People.this, person + " has been deleted.", Toast.LENGTH_SHORT).show();
        mDbHelper.deletePerson(id);
        fillData();
        return true;
    case EDIT_ID:
        Intent i = new Intent(this, PersonEdit.class);
        i.putExtra("_id", id);
        i.putExtra("person", person);
        startActivityForResult(i, ACTIVITY_EDIT);
        return true;
    }
    return super.onContextItemSelected(item);
}