1、首先自定义一个类
public class SelectImagePopupWindow extends PopupWindow {
private View mMenuView;
private Button cancelBtn ;
Context context;
@SuppressLint("InflateParams")
public SelectImagePopupWindow(final Context context,OnClickListener itemsOnClick) {
super(context);
this.context = context;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mMenuView = inflater.inflate(R.layout.layout_dialog_sex, null);
LinearLayout setsharp=(LinearLayout) mMenuView.findViewById(R.id.setsharp);
Button manBtn = (Button) mMenuView.findViewById(R.id.manBtn);
Button woMan = (Button) mMenuView.findViewById(R.id.femaleBtn);
cancelBtn = (Button) mMenuView.findViewById(R.id.cancelBtn);
// 设置按钮监听
cancelBtn.setOnClickListener(itemsOnClick);
manBtn.setOnClickListener(itemsOnClick);
woMan.setOnClickListener(itemsOnClick);
// 设置SelectPicPopupWindow弹出窗体的高
this.setHeight(LayoutParams.WRAP_CONTENT);
// 设置SelectPicPopupWindow的View
this.setContentView(mMenuView);
// 设置SelectPicPopupWindow弹出窗体的宽
this.setWidth(LayoutParams.MATCH_PARENT);
// 设置SelectPicPopupWindow弹出窗体可点击
this.setFocusable(true);
// 设置SelectPicPopupWindow弹出窗体动画效果
this.setAnimationStyle(R.style.PopupAnimation);
// 实例化一个ColorDrawable颜色为半透明
ColorDrawable dw = new ColorDrawable(0x80000000);
// 设置SelectPicPopupWindow弹出窗体的背景
this.setBackgroundDrawable(dw);
// mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
mMenuView.setOnTouchListener(new OnTouchListener() {
@Override
@SuppressLint("ClickableViewAccessibility") public boolean onTouch(View v, MotionEvent event) {
int height = mMenuView.findViewById(R.id.pop_layout) .getTop();
int y = (int) event.getY();
// 如果触及上面的空白部分则销毁
if (event.getAction() == MotionEvent.ACTION_UP)
{
if (y < height || y > height) {
dismiss();
}
}
return true;
}
});
}}
2、其次定义动画
<style name="PopupAnimation" parent="android:Animation">
<item name="android:windowEnterAnimation">
@anim/push_bottom_in
</item>
<item name="android:windowExitAnimation">
@anim/push_bottom_out
</item>
</style>
3、然后自定义布局layout_dialog_sex
4、在用到的地方进行调用
SelectImagePopupWindow menuWindow = new SelectImagePopupWindow (this, itemsOnClick);
menuWindow.showAtLocation(this.findViewById(R.id.mainLayout), Gravity.CENTER | Gravity.CENTER, 0, 0);
//itemsOnClick 主要是对自定义布局上的控件做的点击监听事件
private View.OnClickListener itemsOnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
menuWindow.dismiss();
case R.id.cancle: //to do someting break; default: break; } }};