0

我有一个 ListView,它允许用户长按一个项目来获取上下文菜单。我遇到的问题是确定他们长按了哪个 ListItem 。我有 3 列(ID、文本、评论)。单击时我需要检索 ID 值。

我试过这样做:

@Override
public boolean onContextItemSelected(MenuItem item) {
  if (item.getTitle() == "Delete") {
    View view = getWindow().getDecorView().findViewById(android.R.id.content);
    //The rowId receive the ID clicked from the listview
    rowId = ((TextView)view.findViewById(R.id.ID)).getText().toString();
    showDialog(0);
  } else return false;
  return true;
}

但是,我总是从列表视图的第一项中获取 ID。如果我单击列表视图上的第二个项目,我只会收到列表中的第一个 ID。

请提供任何帮助。

提前致谢。

4

2 回答 2

1

使用以下代码获取选定的行索引 -

public boolean onContextItemSelected(MenuItem item) {
            try {
                AdapterContextMenuInfo ctxMenuInfo;
                try {
                    ctxMenuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
                } catch (ClassCastException e) { 
                    return false;
                }

                 int selectedPostion = ctxMenuInfo.position;
}
于 2012-03-28T13:36:16.073 回答
1

如果您想从所选视图本身中提取信息,请尝试此操作。

AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
View v = info.targetView;
rowId = ((TextView)v.findViewById(R.id.ID)).getText().toString();
于 2012-03-28T13:38:45.107 回答