要显示一个对话框,首先需要在xx.xml下添加一个Button按钮,并添加一个对应id。
单次点击事件对话框:
button.setOnClickListener(new View.OnClickListener(){ @Override
public void onClick(View v) {
//定义对话框的步骤
//1.获取buidlder对象
final AlertDialog.Builder builder =new AlertDialog.Builder(MainActiviy.this);
//2.通过调用builder对象的方法,设置对话框的标题,内容,图标,按钮
builder.setMessage("这是一个简单的对话框");
//3.通过bulider创建简单的对话框
builder.create();
//4.通过builder对象的show方法,显示对话框
builder.show(); 多事件对话框选择:
builder.setMessage("你是一个简单的傻哥")
.setTitle("对话框")
.setIcon(R.drawable.cat)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
button.setText("您点了确定");
}
})
.setNegativeButton("取消",null)
.create()
.show(); }
});
}
点击选择提示对话框:
builder.setItems(new String[]{"红色", "黄色", "绿色"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch(which){
case 0:
button.setText("傻哥");
break
case 1:
button.setText("傻哥1");
break;
case 2:
button.setText("傻哥2");
break; } }
})
.setIcon(R.drawable.cat)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
button.setText("您点了确定");
}
})
.setNegativeButton("取消",null)
.create()
.show(); }
});
} 调用颜色变化:
builder.setSingleChoiceItems(new String[]{"红色","黄色","绿色"},
1,new DialogInterface.OnClickListener(){ @Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
button.setTextColor(getResources().getColor(R.color.colorAccent));
break;
case 1:
button.setTextColor(getResources().getColor(R.color.colorPrimary));
break;
case 2:
button.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
break;
} }
}) .setTitle("对话框")
.setIcon(R.drawable.cat)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
button.setText("您点了确定");
}
})
.setNegativeButton("取消",null)
.create()
.show(); }
});
}
多选对话框
init();
button.setOnClickListener(new View.OnClickListener(){ @Override
public void onClick(View v) {
AlertDialog.Builder builder=new AlertDialog.Builder(Main20170326.this);
final boolean[] checkeds={true,true,false};
final String[] items =new String[]{"红色","黄色","蓝色"};
builder.setMultiChoiceItems(new String[]{"红色","黄色","蓝色"}
, checkeds,new DialogInterface.OnMultiChoiceClickListener(){ @Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
String result="";
for(int i=0; i<checkeds.length;i++){
if(checkeds[i]){
result +=items[i]+"";
}
}
textView.setText(result);
}
})
.setTitle("多选对话框")
.create()
.show();
}
}); }