简体   繁体   English

获取项目LongClicked在ListView中的位置

[英]Get position of the item LongClicked in a ListView

I have a ListView displaying custom views (3 TextViews per item); 我有一个ListView显示自定义视图(每个项目3个TextViews ); I have just implemented a context menu like such: 我刚刚实现了这样的上下文菜单:

// in onCreateView
ListView list = (ListView) view.findViewById(R.id.list);

registerForContextMenu(list);

and

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    if (v.getId() == R.id.list) {
        MenuInflater inflater = getActivity().getMenuInflater();
        inflater.inflate(R.menu.todo_context_menu, menu);
    }
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.edit:
            // your first action code
            return true;
        case R.id.delete:
            // your second action code
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

I wish to know which item has been long clicked (its position in the ListView would be ideal) in order to edit or delete the right one. 我想知道长按一下哪个项(它在ListView位置是理想的)以便编辑或删除正确的项。

How may that be achieved? 如何实现?

@Override
public boolean onContextItemSelected(MenuItem item) {

   AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
   int index = info.position;

  switch (item.getItemId()) {
    case R.id.edit:
        // your first action code
        return true;
    case R.id.delete:
        // your second action code
        return true;
    default:
        return super.onContextItemSelected(item);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM