普通对话框
//普通对话框
public void click1(View v) {
/*
* 这里的上下文只能用this
* 因为
* getApplicationContext 直接返回context (父类)
* this是继承context (子类)
* */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("警告");
builder.setMessage("没网了");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//关闭对话框
dialog.dismiss();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//关闭对话框
dialog.dismiss();
}
});
//必须像Toast一样show出来
builder.show();
}
单选对话框
//单选对话框
public void click2(View v){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("学习的编程语言");
//内部类访问外部类需声明final
final String items[]={"C","Java","Html","C++"};
//-1表示没有选中
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//显示选中的数据
String con= items[which];
Toast.makeText(getApplicationContext(),con,Toast.LENGTH_LONG).show();
//关闭对话框
dialog.dismiss();
}
});
builder.show();
}
多选对话框
//多选对话框
public void click3(View v){
AlertDialog.Builder builder =new AlertDialog.Builder(this);
builder.setTitle("你喜欢的编程语言:");
//内部类访问外部类需声明final
final String items[]={"C","Java","Html","C++"};
//选中的位置
final boolean []checkedItems={true,true,false,false};
final StringBuffer sb=new StringBuffer();
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
}
});
//点击确定显示选中的数据,关闭对话框
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//取出选中的数据
for (int i=0;i<items.length;i++){
if(checkedItems[i]){
String item = items[i];
sb.append(item+" ");
}
}
//显示数据
Toast.makeText(getApplicationContext(),sb.toString(),Toast.LENGTH_LONG).show();
//关闭窗口
dialog.dismiss();
}
});
builder.show();
}
进度条对话框
//进度条对话框
public void click4(View v){
final ProgressDialog dialog=new ProgressDialog(this);
dialog.setTitle("正在加载中:");
//设置成水平线
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//显示
dialog.show();
new Thread(){
@Override
public void run() {
super.run();
dialog.setMax(100);
for(int i=0;i<=100;i++){
dialog.setProgress(i);
//等价于 Thread.sleep(50);但不报异常
SystemClock.sleep(50);
}
//关闭进度条
dialog.dismiss();
}
}.start();
}
网友评论