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);

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

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?
You would use your own custom adapter, then depending on the position of the view, you would inflate a different layout.
How do we show the popup window on click of the overflow menu button? Would apprecaite any help with the question at stackoverflow.com/questions/28834089/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.