在开发的过程中,我们会经常用到Dialog,虽然原生的dialog很优秀,但是面对产品,原生都是没有用的,所以就需要我们自定义布局.写多了,就觉得很烦,就想到了封装,网上看到了一种方式,很值得我们去借鉴,那就是利用构造者模式.
public class CustomBuilderDialog extends Dialog {
private boolean cancelTouchout;
private View view;
private CustomBuilderDialog(Builder builder) {
super(builder.context);
this.cancelTouchout =builder. cancelTouchout;
this.view = builder.view;
}
private CustomBuilderDialog(Builder builder, int resStyle) {
super(builder.context, resStyle);
this.cancelTouchout = builder.cancelTouchout;
this.view = builder.view;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
setCanceledOnTouchOutside(cancelTouchout);
Window window=getWindow();
WindowManager.LayoutParams layoutParams = window.getAttributes();
layoutParams.gravity= Gravity.CENTER;
layoutParams.width= UnitsUtil.getWindowsWidth()/4*3;
layoutParams.height= ViewGroup.LayoutParams.WRAP_CONTENT;
window.setAttributes(layoutParams);
}
public static final class Builder{
private Context context;
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 style(int resStyle) {
this.resStyle = resStyle;
return this;
}
public Builder cancelTouchout(boolean val) {
cancelTouchout = val;
return this;
}
public Builder addViewOnclick(int viewRes,View.OnClickListener listener){
view.findViewById(viewRes).setOnClickListener(listener);
return this;
}
public CustomBuilderDialog build() {
if (resStyle != -1) {
return new CustomBuilderDialog(this, resStyle);
} else {
return new CustomBuilderDialog(this);
}
}
}
}
在使用的时候有一下几个注意点:
第一,必须设置样式,如果不设置样式的话,界面如下图:红色的部分就是多余的
第二,样式@android:color/transparent属性必须为透明,否则如下图
第三:正常的界面
样式:
<style name="MyDialogStyle">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:backgroundDimEnabled">true</item>
</style>