【问题标题】:Android NULL menuInfo in onCreateContextMenu and onContextItemSelected only with manual call to openContextMenu in onListItemClick. Long click worksonCreateContextMenu 和 onContextItemSelected 中的 Android NULL menuInfo 仅通过手动调用 onListItemClick 中的 openContextMenu。长按有效
【发布时间】:2013-10-19 20:46:03
【问题描述】:

我已经解析了这里的很多帖子,但没有发现与我的问题很相似的东西。

基本上我正在尝试在onListItemClick 中调用openContextMenu(l)。这样做会创建一个没有menuInfo 的上下文菜单。执行长按将正常工作。执行长按后,我的代码将开始工作并实际得到一个不为空的menuInfo

我有一个ListActivity,里面有一个SimpleCursorAdapter,它从SQL 中获取数据。

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

...

【问题讨论】:

    标签: android listview null click contextmenu


    【解决方案1】:

    我今天遇到了一个非常相似的问题,解决方法出乎意料地简单,但我不明白为什么,但无论如何我都会在这里发布。

    @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 为 true 则返回 false 以便上下文菜单确实显示(如果 onItemLongClick() 返回 true,则不会显示上下文菜单)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-15
      相关资源
      最近更新 更多