今天分享下自己模仿淘宝退出时的一个自定义对话框,这个效果在很多地方都有实现,今天就模仿一个,我们来看看效果:
思路:首先ConfirmDialog类继承AlertDialog:这样才会有显示的效果,第二个就是让内容完全覆盖掉,用getWindow.setContentView(layout);layout为自定义的layout,然后show出来就ok。
ConfirmDialog.calss如下:
public class ConfirmDialog extends AlertDialog {
Context context;
public Button cancelButton;
public Button okButton;
public TextView messageTextView;
public ConfirmDialog(Context context) {
super(context);
this.context = context;
}
public ConfirmDialog(Context context, int theme) {
super(context, theme);
this.context = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(context);
layout.setGravity(Gravity.CENTER_HORIZONTAL);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.WHITE);
messageTextView = BaseView.creatTextView(context, "确认退出吗?");
LayoutParams messageParams = new LayoutParams(244, LayoutParams.WRAP_CONTENT);
messageParams.setMargins( 4,24, 0,24);
messageTextView.setLayoutParams(messageParams);
layout.addView(messageTextView);
LinearLayout layout1 = new LinearLayout(context);
layout1.setOrientation(LinearLayout.HORIZONTAL);
// noneButton
LayoutParams btnParams = new LayoutParams(LayoutParams.FILL_PARENT, DensityUtil.dip2px(context, 36));
btnParams.setMargins(4, 0, 2, 4);
btnParams.weight = 1;
cancelButton = BaseView.createGrayButton(context, "取 消");
cancelButton.setLayoutParams(btnParams);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConfirmDialog.this.dismiss();
}
});
okButton = BaseView.createOrangeButton(context, "确 认");
LayoutParams okButtonParams = new LayoutParams(LayoutParams.FILL_PARENT,36);
okButtonParams.weight = 1;
okButton.setLayoutParams(okButtonParams);
layout1.addView(cancelButton);
layout1.addView(okButton);
layout.addView(layout1);
getWindow().setContentView(layout);
}
@Override
public void show() {
super.show();
}
}
关键是这句话:getWindow().setContentView(layout);
使用:
ConfirmDialog confirmDialog = new ConfirmDialog(context);confirmDialog.show();
confirmDialog.okButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//ok操作
}
});