前言:
dialog和PopupWindow在开发中是比较常用的两个View,二者都需要在Window上显示出来,正所谓有view的地方就有window,同时二者都需要调用setContentView方法,为什么请查看文章(Activity Window View三者之间的关系 https://blog.csdn.net/xgangzai/article/details/81390630)。
封装的dialog
dialog采用构造者模式,同属包括内部某按钮点击事件的接口回调,以及EditText等控件输入后在Activity中值的获取等。
- 自定义dialog
public class CustomDialog extends Dialog {
private Context context;
private int height, width;
private boolean cancelTouchOut;
private View view;
private CustomDialog(Builder builder) {
super(builder.context);
context = builder.context;
height = builder.height;
width = builder.width;
cancelTouchOut = builder.cancelTouchOut;
view = builder.view;
}
private CustomDialog(Builder builder, int resStyle) {
super(builder.context, resStyle);
context = builder.context;
height = builder.height;
width = builder.width;
cancelTouchOut = builder.cancelTouchOut;
view = builder.view;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
setCanceledOnTouchOutside(cancelTouchOut);
Window win = getWindow();
WindowManager.LayoutParams lp = win.getAttributes();
lp.gravity = Gravity.CENTER;
lp.height = height;
lp.width = width;
win.setAttributes(lp);
}
public static final class Builder {
private Context context;
private int height, width;
private boolean cancelTouchOut;
private View view;
private int resStyle = -1;
public Builder(Context context) {
this.context = context;
}
public Builder view(int resView) {
view = LayoutInflater.from(context).inflate(resView, null);
return this;
}
public Builder heightpx(int val) {
height = val;
return this;
}
public Builder widthpx(int val) {
width = val;
return this;
}
public Builder heightdp(int val) {
height = DensityUtil.dip2px(context, val);
return this;
}