Showing context menus for two listviews in same activity - Android Java
20 August 2015By Bhavyanshu Parasher
I wrote this for my own reference but I hope this helps someone looking for a solution to register two different ListViews to show respective context menus in the same activity layout.
For this, open your layout file for the acitivity. Add two listviews. Skip this step if you already have added two listviews in your activity layout.
So now we have two listviews, we need to create two seperate menu layouts. In your res/menu/ create two files,
Now finally let us see how to handle different listviews. In onCreateContextMenu() we use conditional statement and compare the view IDs like,
Then in onContextItemSelected() we handle whatever the user presses just like we normally do. It does not matter what menu it belongs to because we are already handling all that in onCreateContextMenu()
Now finally we need to register our listviews for context menu. Add in onCreate() method,
That’s all. Try to run the app and test it out. Leave a comment below if you want to ask anything.