我已经分析了这里的很多帖子,没有发现任何类似我的问题。
基本上,我试图在openContextMenu(l)
中调用onListItemClick
。这样做会创建一个没有menuInfo
的上下文菜单。执行长单击将正常工作。在执行长单击之后,我的代码将开始工作,并实际得到一个不为空的menuInfo
。
我有一个ListActivity
填充了一个SimpleCursorAdapter
从SQL
获取数据。
在我的oncreate中,我registerForContextMenu(getListView())
。
我也试过在通话前使用registerForContextMenu(l)
。
任何帮助都将不胜感激!谢谢。
以下是我的代码示例:
public class MY_Activity extends ListActivity {
...
@Override
public void onCreate(Bundle savedInstanceState) {
...
UpdateTable();
registerForContextMenu(getListView());
}
...
@Override
public void onListItemClick(ListView l, View view, int position, long id) {
super.onListItemClick(l, view, position, id);
//THIS DOESNT WORK UNLESS A LONG CLICK HAPPENS FIRST
//registerForContextMenu(l); //Tried doing it here too
openContextMenu(l);
//unregisterForContextMenu(l); //Then unregistering here...
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
//menuInfo will be null here.
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "One");
menu.add(0, v.getId(), 0, "Two");
menu.add(0, v.getId(), 0, "Three");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if(info == null) {
Log.e("","NULL context menu intem info...");
return false;
}
}
public void UpdateTable() {
cursor = DatabaseHelper_Main.GetCursor(my_id);
cursorAdapter = new SimpleCursorAdapter(this, R.layout.my_listview_entry,
cursor, fields, fieldResources, 0);
setListAdapter(cursorAdapter);
}
...
最佳答案
我今天遇到了一个非常相似的问题,修复过程出乎意料地简单,但我不明白为什么,但我还是会把它贴在这里。
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
m_contextMenu = true;
registerForContextMenu(parent);
m_listView.showContextMenuForChild(view);
unregisterForContextMenu(parent);
m_contextMenu = false;
}
我使用m_ContextMenu布尔值来指示正在显示上下文菜单,我有一个OnTimeLongClickListener,如果m_ContextMenu为true,则返回false,以便上下文菜单确实显示(如果OnTimeLongClick()返回true,则不会显示上下文菜单)。