OnCreateContextMenu 和 ListView 项 [英] OnCreateContextMenu and ListView items

查看:24
本文介绍了OnCreateContextMenu 和 ListView 项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个项目的 LisView.为此,我连接了一个 OnItemClickListener(作为内部类),如下所示:

I have a LisView with several items. To this I've connected an OnItemClickListener (as an inner class), like this:

lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Toast.makeText(ShoppingListApp02Activity.this, "List item selected:" +  
    items.get(position).getId(), Toast.LENGTH_LONG).show();
    }
});

很明显,选择一个条目会显示该条目的对象的元素,在本例中是选定的 Item 对象的 ID(不是列表 ID,而是对象 ID,在创建 ArrayList 项目时设置).这很好用,让我可以对所选项目做任何我想做的事情.

As is obvious, selecting an entriy displays elements of the object of that entry, in this example the selected Item object's ID (not the list ID, but the objects ID, set when creating the ArrayList items). This works nicely, and enables me to do anything I want with the selected item(s).

现在我还想有一个长按"侦听器,它会打开所选 ListView 项目的上下文菜单.我怎么做?我已经能够将 onCreateContextMenu 侦听器附加到 ListView,但我不知道如何像使用 onItemClickListener 一样获取 ArrayList 的元素?

Now I'd like to also have a "long-click" listener her, which opens a context menu for the selected ListView item. How do I do that? I've been able to attach an onCreateContextMenu listener to the ListView, but I don't see how I can get the elements of the ArrayList as with the onItemClickListener?

这是我所拥有的:

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {  
    menu.add(0, v.getId(), 0, "Something");
    menu.add(0, v.getId(), 0, "Something else");  
}

由于 OnCreateConextMenu 采用与 OnItemClickListener 不同的参数,我如何像在 OnItemClickListener 中一样访问 ArrayList 的元素?

Since OnCreateConextMenu takes different parameters than the OnItemClickListener, how to I access the ArrayList's elements like in the OnItemClickListener?

推荐答案

如果您决定仍要使用上下文菜单范例:

If you decide you still want to use the context menu paradigm:

在处理列表时考虑这一点:

Consider this for working with lists:

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {  

    // Get the list
    ListView list = (ListView)v;

    // Get the list item position    
    AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo;
    int position = info.position

    // Now you can do whatever.. (Example, load different menus for different items)
    list.getItem(position);
    ...
}

这篇关于OnCreateContextMenu 和 ListView 项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆