我应该如何制作自定义MenuItem,与所附图片菜单中的第一行完全相同(Google Chrome应用的截图)
我在onCreateOptionsMenu
中尝试了以下代码,其中R.layout.menu_top_row
是第一行的布局。但在我的情况下只出现一个空行?我可以显示其余选项,但无法显示第一行。
View child = getLayoutInflater().inflate(R.layout.menu_top_row, null);
MenuItem menuItem=menu.add("");
menuItem.setActionView(child);
答案 0 :(得分:3)
Taken from this stack overflow answer:
PopupMenu用于显示Menus,并且确实没有一种自定义菜单项外观的好方法。如果您想要更灵活的内容,您的答案是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();
}