问题
How should i make a Custom MenuItem, exactly like the first row in the menu of the attached picture ( screenshot of Google Chrome app)
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:
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();
}
来源:https://stackoverflow.com/questions/28030579/custom-menu-item-in-overflow-menu