-
-
Save deakjahn/b12f10e3951cf595664c to your computer and use it in GitHub Desktop.
public class MenuPreference extends ListPreference { | |
private View anchor; | |
public MenuPreference(Context context) { | |
super(context); | |
} | |
public MenuPreference(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
@Override | |
protected View onCreateView(ViewGroup parent) { | |
return anchor = super.onCreateView(parent); | |
} | |
@Override | |
protected void showDialog(Bundle state) { | |
final PopupMenu popup = new PopupMenu(getContext(), anchor, Gravity.TOP); | |
final Menu menu = popup.getMenu(); | |
for (int i = 0; i < getEntries().length; i++) { | |
MenuItem item = menu.add(1, i, Menu.NONE, getEntries()[i]); | |
item.setChecked(item.getTitle().equals(getEntry())); // 1 | |
} | |
menu.setGroupCheckable(1, true, true); // 2 | |
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { | |
@Override | |
public boolean onMenuItemClick(MenuItem item) { | |
popup.dismiss(); | |
String value = getEntryValues()[item.getItemId()].toString(); | |
if (callChangeListener(value)) | |
setValue(value); | |
return true; | |
} | |
}); | |
popup.show(); | |
} | |
} |
I see. I'm not sure I'm a fan of this look, it would make more sense I think if it matched the parent's width rather than just wrapping its content.
I happen to like this look but there would be an alternative. I have a replacement PopupMenu somewhere, based on PopupWindow instead. Being your own window, you can size and modify it freely. The reason to write it was to allow free showAtLocation() placement, because PopupMenu doesn't allow this, its placement is automatic.
Not that it would be that complicated, the window has a single ListView, and a MenuAdapter fills it. A nine-patch gives it the same look as the original menu.
Would a spinner work here instead? Specifically to achieve the effect of having the popup appear on top of the preference rather than below/above it
A MenuPreference showing a menu instead of an old ListPreference (a modal simple dialog), as recommended by http://www.google.com/design/spec/components/menus.html#menus-simple-menus.
Items 1 and 2 (see comments) are optional if you want to have radio buttons. Checkboxes can be specified similarly.