4

How should i make a Custom MenuItem, exactly like the first row in the menu of the attached picture ( screenshot of Google Chrome app)enter image description here

I have tried the below code in onCreateOptionsMenu, where R.layout.menu_top_row is the layout for the first row.But only a blank row comes up in my case? I am able to display rest of the options, but unable to display the first row.

View child = getLayoutInflater().inflate(R.layout.menu_top_row, null);
    MenuItem menuItem=menu.add("");
    menuItem.setActionView(child);
Diffy
  • 2,339
  • 3
  • 25
  • 47

1 Answers1

4

Taken from this stack overflow answer:

A PopupMenu is meant for displaying Menus and there really isn't a good way of customizing the appearance of the menu items. If you want something more flexible, your answer is ListPopupWindow.

private static final String TITLE = "title";
private static final String ICON = "icon";

private List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

// Use this to add items to the list that the ListPopupWindow will use
private void addItem(String title, int iconResourceId) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put(TITLE, title);
    map.put(ICON, iconResourceId);
    data.add(map);
}

// Call this when you want to show the ListPopupWindow
private void showListMenu(View anchor) {
    ListPopupWindow popupWindow = new ListPopupWindow(this);

    ListAdapter adapter = new SimpleAdapter(
            this,
            data,
            android.R.layout.activity_list_item, // You may want to use your own cool layout
            new String[] {TITLE, ICON}, // These are just the keys that the data uses
            new int[] {android.R.id.text1, android.R.id.icon}); // The view ids to map the data to


    popupWindow.setAnchorView(anchor);
    popupWindow.setAdapter(adapter);
    popupWindow.setWidth(400); // note: don't use pixels, use a dimen resource
    popupWindow.setOnItemClickListener(myListener); // the callback for when a list item is selected
    popupWindow.show();
}
Community
  • 1
  • 1
Andrew Orobator
  • 7,978
  • 3
  • 36
  • 36
  • Doesn't this allow only the same type of row (icon+text)? How could this be used to show a different row (like the first one in the menu shown in the question) which has multiple icons? – Bootstrapper Feb 24 '15 at 20:24
  • You would use your own custom adapter, then depending on the position of the view, you would inflate a different layout. – Andrew Orobator Feb 24 '15 at 22:42
  • How do we show the popup window on click of the overflow menu button? Would apprecaite any help with the question at https://stackoverflow.com/questions/28834089/anchor-popup-menu-over-overflow-button?lq=1 – source.rar Mar 09 '15 at 22:00