Skip to content

Instantly share code, notes, and snippets.

@ZacSweers
Forked from deakjahn/gist:b12f10e3951cf595664c
Last active June 22, 2017 06:00
Show Gist options
  • Save ZacSweers/ca87c4049015d0c93181 to your computer and use it in GitHub Desktop.
Save ZacSweers/ca87c4049015d0c93181 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();
}
}
@ZacSweers
Copy link
Author

Adding a comment from the original gist:

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment