Reputation: 159
I'm having an issue where onCreateContextMenu is being called every single time I long press an item on my listview. Since it's being called every time, it was overwriting any changes I make to the menu items.
in my onCreate() of my MainActivity I have this.
trackingList = (ListView) findViewById(R.id.trackingList);
listAdapter = new SummonerAdapter(MainActivity.this, summonerNames);
trackingList.setAdapter(listAdapter);
registerForContextMenu(trackingList);
in my onCreateContextMenu()
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.list_context_menu, menu);
this.menu = menu;
toggle = menu.findItem(R.id.postGameNotif);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
int listPosition = info.position -1;
SharedPreferences prefs = getApplicationContext().getSharedPreferences("summoner_prefs", MODE_PRIVATE);
boolean postNotif = prefs.getBoolean(summonerNames.get(listPosition) + "_postNotif",false);
if (postNotif){
toggle.setTitle("Disable post-game notifications");
}
else
toggle.setTitle("Enable post-game notifications");
}
my onPrepareOptionsMenu() is empty.
As a side effect of this, when I call showContextMenu() from another class, it will crash unless I have previous long-pressed a list item first. But it will work as intended if I have already opened up the context menu once. I found the same issue here but it didn't seem to be resolved.
It appears that when I call showContextMenu() from my other class, it calls onCreateContextMenu() again, but menuInfo is null.
Upvotes: 0
Views: 322
Reputation: 10869
Try this, for your scenario instead of registering a context menu for your listview, add onLongClickListener to every child view in your Listview, that is override getView() and add the listener to it, and call showContextMenu() every time the listener is triggered, and modify your oncreateOptions menu by removing the adapter info because if you handle in it in the getView you very well know its position.
your position should be final before it can fit into the listener or you could find another way to pass it through your listener, by tag or a new int variable
Hope it helps
Upvotes: 0