一、标准对话框Dialog
使用AlertDialog类和AlertDailog.Builder类
标准效果图
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle("对话框再此");
builder.setMessage("hello,我是对话框");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this,"显示标准对话框",Toast.LENGTH_SHORT).show();
}});
builder.setNegativeButton("取消",null);
AlertDialog dialog=builder.create();
dialog.setCanceledOnTouchOutside(true);//点击屏幕外面dialog会消失
dialog.show();
二、列表对话框
列表效果图
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher);
final String arr[]=getResources().getStringArray(R.array.cities);
builder.setTitle("列表对话框:城市");
builder.setItems(R.array.cities, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this,"选择的城市:"+arr[i],Toast.LENGTH_SHORT).show();
}});
AlertDialog dialog=builder.create();
dialog.setCanceledOnTouchOutside(true);//点击屏幕外面dialog会消失
dialog.show();
三、单选对话框
单选对话框效果图
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher);
final String arr[]=getResources().getStringArray(R.array.cities);
builder.setTitle("单选对话框:城市");
//默认选中第一个城市
builder.setSingleChoiceItems(R.array.cities, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this,"选择的城市:"+arr[i],Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}});
AlertDialog dialog=builder.create();
dialog.setCanceledOnTouchOutside(true);//点击屏幕外面dialog会消失
dialog.show();
四、多选对话框
多选对话框的取值问题,可以看CheckBox那一章
多选对话框效果图
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher);
final String arr[]=getResources().getStringArray(R.array.cities);
builder.setTitle("多选对话框:城市");
//默认初始化选中选项
boolean checked[]={false,false,true,true,false};
builder.setMultiChoiceItems(R.array.cities, checked, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i, boolean b) {
Toast.makeText(MainActivity.this,"选择城市:"+arr[i],Toast.LENGTH_SHORT).show();
}});
AlertDialog dialog=builder.create();
dialog.setCanceledOnTouchOutside(true);//点击屏幕外面dialog会消失
dialog.show();