这应该适用于 API 4(但未经测试,YMMV)。例如:
如果您使用的是 ActionBarSherlock,则可以使用 IcsListPopupWindow 类。在 onCreate 中为其设置一些属性。您还需要继承一个 ArrayAdapter。
在 onCreate() 中:
mPopupMenu = new IcsListPopupWindow(getContext());
mAdapter = new PopupMenuAdapter(this, android.R.layout.simple_list_item_1, yourArrayOfPopupMenuItems);
mPopupMenu.setAdapter(mAdapter);
mPopupMenu.setModal(true);
mPopupMenu.setOnItemClickListener(this);
mPopupMenu.setOnDismissListener(this); // only if you need it
片段/活动中的内部类:
private class PopupMenuAdapter extends ArrayAdapter<PopupMenuItem> {
Context context;
int layoutResourceId;
PopupMenuItem data[] = null;
public PopupMenuAdapter(Context context, int layoutResourceId, PopupMenuItem[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
// initialize a view first
if (view == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
view = inflater.inflate(layoutResourceId, parent, false);
}
PopupMenuItem pItem = data[position];
TextView text = (TextView)view.findViewById(android.R.id.text1);
text.setText(pItem.textResId);
text.setCompoundDrawablesWithIntrinsicBounds(pItem.iconResId, 0, 0, 0);
return view;
}
}
// ... PopupMenuItem is just a container
private static class PopupMenuItem {
public int iconResId;
public int textResId;
public PopupMenuItem(int iconResId, int textResId) {
this.iconResId = iconResId;
this.textResId = textResId;
}
}
当你需要展示它时(比如View.OnClickListener)
mPopupMenu.setContentWidth(getActivity().getWindowManager().getDefaultDisplay().getWidth() / 2);
PopupAdapter.notifyDataSetChanged(); // if you change anything
mPopupMenu.setAnchorView(yourAnchorView);
mPopupMenu.show();
在您的 OnItemClickListener 中
请务必致电mPopupMenu.dismiss()!
希望这会有所帮助!感谢 Jake Wharton 的 ABS!