Custom Menu on button click as drop down

Rohan Kandwal picture Rohan Kandwal · Sep 17, 2014 · Viewed 9.4k times · Source

I am trying to implement the action bar functionality of the flipkart app.Flipkart App screenshot.

For this I have successfully created a custom Action Bar but I am facing problems in showing the menu as drop down on overflow icon click.

If I try Android Option Menu on button click then on I am getting the menu without icons (4.2.2) at the bottom center of my screen. Using a custom dialog or alert dialog fades the background and they also appear on the center of the screen.

What should I do to get the functionality similar as shown in the image above?

Answer

Anton picture Anton · Nov 2, 2015

You can easily use ListPopupWindow and any convenient for you adapter:

// create any adapter with any data, just as for ordinary ListView
    SimpleAdapter simpleAdapter= new SimpleAdapter(this, dataSet, android.R.layout.simple_list_item_2,
                            new String[] {"Name", "Tel. no."},
                            new int[] {android.R.id.text1, android.R.id.text2});

ListPopupWindow listPopup = new ListPopupWindow(this); // feed context to ListPopupWindow
listPopup.setAdapter(simpleAdapter); // set adapter to created ListPopupMenu

listPopup.setAnchorView(findViewById(id)); 
// id - any id of any view on the screen. Under this view popup appears. It may be MenuItem as well

listPopup.setWidth(getWidestView(simpleAdapter)); 
// as popup width equals the anchor width, use getWidestView method for proper list displaying. 
// ListPopupWindow.WRAP_CONTENT won't work here

listPopup.show();

getWidestView snippet you can find here: https://stackoverflow.com/a/13959716/4890659