onCreateContextMenu和onContextItemSelected中的Android NULL menuInfo仅在onListItemClick中手动调用openContextMenu。长按是有效的

时间:2013-10-11 17:15:52

标签: android listview null click contextmenu

我在这里解析了很多帖子,但没有发现任何类似我的问题。

基本上我想在openContextMenu(l)中致电onListItemClick。这样做会创建一个没有menuInfo的上下文菜单。执行长按可以正常工作。执行长按后,我的代码将开始工作,并实际获得一个非空的menuInfo

我的ListActivity填充了SimpleCursorAdapter,可以抓取SQL的数据。

在我的onCreate I registerForContextMenu(getListView())中。 我还尝试在registerForContextMenu(l)来电之前使用openContextMenu(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);
}

...

1 个答案:

答案 0 :(得分:0)

今天我遇到了一个非常类似的问题,修复工作出乎意料地简单,但我不明白为什么,但我还是会在这里发布。

@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布尔值来指示正在显示上下文菜单,我有一个onItemLongClickListener,如果m_contextMenu为真,则返回false,以便上下文菜单显示(如果onItemLongClick()返回true,则它赢得了&#39; t显示上下文菜单。)