【问题标题】:Detecting which selected item (in a ListView multicolumn) spawned the ContextMenu (Android)检测哪个选定项目(在 ListView 多列中)产生了 ContextMenu (Android)
【发布时间】:2012-03-28 13:20:04
【问题描述】:

我有一个 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。

请帮忙。

提前致谢。

【问题讨论】:

    标签: android listview contextmenu multiple-columns long-press


    【解决方案1】:

    使用下面的代码获取选中的行索引 -

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

    【讨论】:

      【解决方案2】:

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

      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
      View v = info.targetView;
      rowId = ((TextView)v.findViewById(R.id.ID)).getText().toString();
      

      【讨论】:

        猜你喜欢
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 2015-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多