ListView元素上下文菜单

时间:2012-12-14 16:58:14

标签: android listview contextmenu element

我有一个带有一些元素的ListView。我想检索运行上下文菜单的元素的id(通过长按)。但是遵循以下代码:

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_adapter);

    /*non relevant code was omitted*/
    registerForContextMenu(this.getListView());

}

    @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info){

    Log.i("view", String.valueOf(v.findFocus().getId()) );

    super.onCreateContextMenu(menu,  v, info);
    getMenuInflater().inflate(R.menu.activity_adapter_context_menu, menu);
}

始终返回相同的id,即ListView视图的id而不是ListView元素id。我尝试了另外一些选择,但冷却找不到解决方案。如何解决?

2 个答案:

答案 0 :(得分:0)

为listView设置onItemClickListener。在重写方法上,获取视图ID

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

    String id = view.getId().toString();

    //open context menu now
    view.showContextMenu();
}

注意:只注册一次上下文菜单。

regsiterForContextMenu(listView);

答案 1 :(得分:0)

如果您想获取列表项ID,请使用

lv.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                return false;
            }
        });