Last active
August 29, 2015 14:11
-
-
Save deakjahn/b12f10e3951cf595664c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.