Inappropriate Context Menu within a Fragment

Dennis picture Dennis · Dec 29, 2013 · Viewed 11.8k times · Source

I have an activity with a Navigation Drawer and a fragment. Each of them has his own ListView with a Contextual Menu.

The Context Menu inside the navigation drawer works fine.

The problem is with the menu inside the fragment. When I enter the fragment's context menu, BOTH navigation drawer's menu AND fragment's menu are displayed.

Activity's methods

@Override
protected void onCreate(Bundle savedInstanceState) {
    registerForContextMenu(mDrawerList); // mDrawrList is the navigation drawer's ListView
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId()) {
    case R.id.action_edit:
        // Do some stuff
        return true;
    case R.id.action_delete:
        // Do some stuff
        return true;
    }
    return super.onContextItemSelected(item);
}

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

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.drawer, menu);
}

Fragment's methods

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mListView = (ListView) view.findViewById(R.id.list);
    registerForContextMenu(mListView);
    // ...
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId()) {
    case R.id.action_edit:
        // Do some stuff
        return true;
    case R.id.action_delete:
        // Do some stuff
        return true;
    }
    return super.onContextItemSelected(item);
}

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

    getActivity().getMenuInflater().inflate(R.menu.fragment_menu, menu);
}

Thank you in advance.

Answer

Dennis picture Dennis · Jan 1, 2014

Solved.

The problem was that the activity's onCreateContextMenu was called.

I just removed super.onCreateContextMenu(menu, v, menuInfo); from the fragment's onCreateContextMenu method.

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

    getActivity().getMenuInflater().inflate(R.menu.fragment_menu, menu);
}

Hope it'll help someone.