AlertDialog代码示例
AlertDialog是一个带有确定取消按钮的系统弹窗,因为是系统控件,不需要在layout.xml中注册,直接使用代码即可.
void showAlert(){
AlertDialog.Builder dialog = new AlertDialog.Builder(SubActivity.this);
dialog.setTitle("This is Dialog");
dialog.setMessage("Something important.");
dialog.setCancelable(false);
dialog.setPositiveButton("好", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//点击确定,窗口会自动关闭
}
});
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//点击取消,窗口会自动关闭
}
});
dialog.show();
}
解释
setPositiveButton(确定)和setNegativeButton(取消)分别设置点击之后的动作.
最后使用show()方法调出dialog;
ProgressDialog示例
ProgressDialog和AlertDialog非常类似,它没有两个按钮,只有一个loading动画.
void showProgress(){
ProgressDialog progressDialog = new ProgressDialog(SubActivity.this);
progressDialog.setTitle("This Title");
progressDialog.setMessage("Plese wait");
progressDialog.setCancelable(true);
progressDialog.show();
}
setCancelable() 解释
这两个控件都有setCancelable()方法;
当传入值为true时,点击弹窗之外的空白区域可以关闭弹出窗.