gpt4 book ai didi

java - Android:Listview 长按上下文菜单问题

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:23 24 4
gpt4 key购买 nike

在长时间按住 ListView 条目并显示各种选项后,我试图打开上下文菜单。但是,只要按住不执行/调用任何操作,我就无法执行。

这是我用来调用上下文菜单的代码:

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

MenuItem delete = menu.add("delete");
MenuItem edit = menu.add("edit");
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
}

我也试过了,也没用:

@Override
public void onCreateContextMenu(ContextMenu menu,
View v, ContextMenuInfo menuInfo) {
menu.add(0, 1, 0, "Edit");
menu.add(0, 2, 1, "Rename");
menu.add(0, 3, 2, "Delete");
super.onCreateContextMenu(menu, v, menuInfo);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);

if(item.getTitle().equals("Edit")) {
//Edit code
} else if(item.getTitle().equals("Rename")) {
//Rename code
} else if(item.getTitle().equals("Delete")) {
//Delete code
}
return true;
};

MainActivity 代码(仅相关部分):

public class MainActivity extends Activity {
private List<CountElement> myElements = new ArrayList<CountElement>();
ListView list;
ArrayAdapter<CountElement> adapter;

/*
Users enters needed listview items, code not shown here. It works fine however -
all needed elements are displayed correctly.
*/

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

adapter = new MyListAdapter();
list = (ListView) findViewById(R.id.listView1);
list.setAdapter(adapter);
registerForContextMenu(list);
}

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

MenuItem delete = menu.add("delete");
MenuItem edit = menu.add("edit");
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
}

private class MyListAdapter extends ArrayAdapter<CountElement> {
//Custom adapter code here
}
}

非常感谢任何帮助。谢谢!

最佳答案

好吧,我想通了。在我的自定义 listAdapter 中,我在 listView 上添加了一个 setOnItemLongClickListener。这个 setOnItemLongClickListener 有一个警报显示我需要的选项。这样:

list.setOnItemLongClickListener(new OnItemLongClickListener() { //list is my listView

@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int pos, long id) {
//Whatever you wanna do
}
});

关于java - Android:Listview 长按上下文菜单问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25813170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com