Context Menu in Fragment uses ListView from a different Fragment: registerForContextMenu(getListView())

I managed to figure this out finally!

It turns out it wasn't just calling the context menu for the wrong ListView, the context menu was being called for ALL fragments.

This was solved by using getUserVisibleHint() in an if statement within the onContextItemSelected method, so that if the Fragment the context menu was called for was not visible, it would return false, but if it was the currently visible Fragment, it would execute the proper code, meaning is skips over Fragments that are not the intended Fragment. I had tried getUserVisibleHint() already in a different way but I wasn't thinking about the problem from the right angle then.

Here's an example of the solution.

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (getUserVisibleHint()) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int dataID = data.get(info.position).getDataID();
        String dataName = data.get(info.position).getDataName();

        Activity activity = getActivity();
        if(activity instanceof MainActivity) {
            switch (item.getItemId()){
            case R.id.context_ringtone:
                ((MainActivity) activity).setRingtone(dataID, dataName);
                return true;
            case R.id.context_notification:
                ((MainActivity) activity).setNotification(dataID, dataName);
                return true;
            case R.id.context_alarm:
                ((MainActivity) activity).setAlarm(dataID, dataName);
                return true;
            case R.id.context_sd_card:
                ((MainActivity) activity).saveFile(dataID, dataName);
                return true;
            default:
                return super.onContextItemSelected(item);
            }
        }
    }
    return false;
}