Android listview 长按点击事件。(两种方法)

listview 自带setOnItemLongClickListener实现。

list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "长点击了" + position + "项",
                        Toast.LENGTH_SHORT).show();
                return true;
            }
        });

另一种方法:

    private void ItemOnLongClick() {
//注:setOnCreateContextMenuListener是与下面onContextItemSelected配套使用的
        list
                .setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {

                    public void onCreateContextMenu(ContextMenu menu, View v,
                                                    ContextMenu.ContextMenuInfo menuInfo) {
                        menu.add(0, 0, 0, "分享");
                        menu.add(0, 1, 0, "收藏");
                        menu.add(0, 2, 0, "删除");

                    }
                });
    }

    // 长按菜单响应函数
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        MID = (int) info.id;// 这里的info.id对应的就是数据库中_id的值

        switch (item.getItemId()) {
            case 0:
                // 操作
                Toast.makeText(MainActivity.this,
                        "分享",
                        Toast.LENGTH_SHORT).show();
                break;

            case 1:
                // 操作
                break;

            case 2:
                // 操作
                break;

            default:
                break;
        }

        return super.onContextItemSelected(item);

    }

你可能感兴趣的:(编程代码)