6 android contextmenu arraylist android-listview
我有一个带有几个项目的LisView.为此我连接了OnItemClickListener(作为内部类),如下所示:
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();
}
});
Run Code Online (Sandbox Code Playgroud)
很明显,选择一个entriy会显示该条目对象的元素,在本例中是所选Item对象的ID(不是列表ID,而是创建ArrayList项时设置的对象ID).这很好用,让我可以用选定的项目做任何我想做的事情.
现在我想要一个"长按"监听器,打开所选ListView项的上下文菜单.我怎么做?我已经能够将一个onCreateContextMenu监听器附加到ListView,但是我没有看到如何使用onItemClickListener获取ArrayList的元素?
这是我得到的:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.add(0, v.getId(), 0, "Something");
menu.add(0, v.getId(), 0, "Something else");
}
Run Code Online (Sandbox Code Playgroud)
由于OnCreateConextMenu采用与OnItemClickListener不同的参数,如何在OnItemClickListener中访问ArrayList的元素?
Eya*_*ran 13
如果您决定仍想使用上下文菜单范例:
考虑这个用于处理列表:
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);
...
}
Run Code Online (Sandbox Code Playgroud)
而不是弄乱上下文菜单(在广泛的上下文中使用 - 如在PC中右键单击),ListView提供onItemLongClick事件,这更容易实现.例如:
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
这将帮助您在一行中实现长按操作.
在行视图上的长按事件的事件处理程序中打开视图的上下文菜单.
convertView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
((Activity)mContext).openContextMenu(v);
return true;
}
});
Run Code Online (Sandbox Code Playgroud)
这样,视图上的单击和长按上下文菜单都适用于listview行项目.
| 归档时间: |
|
| 查看次数: |
34345 次 |
| 最近记录: |