开发者

How do I get the text from a context menu?

I have a ListActivity with a list of names (Jacob, Will, Matt, etc.). I have a contextMenu which gives the user the option to edit or delete the person. I know how to find the id to perform the edit and delete func开发者_高级运维tionality, but I can't figure out how to get the person's name to be added to the intent extras or to add a toast when a delete occurs.

Here is a snippet of code that I'm using for the context menu:


@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);
}


Copy paste from my code:

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() is for Activities that extends from ListActivity. If you are not using it, get the ListView and afterwards the adapter.


Thank you Macarse. I somehow stumbled across the answer to my own question. It seems to be working correctly.


@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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜