packagecom.itheima.dialog;importandroid.os.Bundle;importandroid.app.Activity;importandroid.app.AlertDialog;importandroid.app.AlertDialog.Builder;importandroid.content.DialogInterface;importandroid.content.DialogInterface.OnClickListener;importandroid.content.DialogInterface.OnMultiChoiceClickListener;importandroid.view.Menu;importandroid.view.View;importandroid.widget.Toast;public class MainActivity extendsActivity {
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}//确定取消对话框
public voidclick1(View v){
AlertDialog.Builder builder= new Builder(this);//设置图标
builder.setIcon(android.R.drawable.alert_dark_frame);//设置标题
builder.setTitle("欲练此功必先自宫");//设置文本
builder.setMessage("李志平,想清楚哦");//设置确定按钮
builder.setPositiveButton("确定", newOnClickListener() {
@Overridepublic void onClick(DialogInterface dialog, intwhich) {
Toast.makeText(MainActivity.this, "感谢使用本软件,再见", 0).show();
}
});//设置取消按钮
builder.setNegativeButton("取消", newOnClickListener() {
@Overridepublic void onClick(DialogInterface dialog, intwhich) {
Toast.makeText(MainActivity.this, "若不自宫,一定不成功", 0).show();
}
});//使用创建器,生成一个对话框对象
AlertDialog ad =builder.create();
ad.show();
}//单选对话框
public voidclick2(View v){
AlertDialog.Builder builder= new Builder(this);
builder.setTitle("请选择性别");final String[] items = new String[]{//局部变量在内部类使用要final
"男","女"};
builder.setSingleChoiceItems(items,-1, new OnClickListener() {//-1默认被选择的//which:用户所选的条目的下标//dialog:触发这个方法的对话框
@Overridepublic void onClick(DialogInterface dialog, intwhich) {
Toast.makeText(MainActivity.this, "您选择的是:" + items[which], 0).show();//关闭对话框
dialog.dismiss();
}
});
builder.show();
}//多选对话框
public voidclick3(View v){
AlertDialog.Builder builder= new Builder(this);
builder.setTitle("请选择您觉得帅的人");final String[] items = new String[]{//多选条目
"侃哥","赵帅哥","赵老师","赵师兄"};final boolean[] checkedItems = new boolean[]{//checkedItems默认哪些是被选中的,
true,true,false,false};
builder.setMultiChoiceItems(items, checkedItems,newOnMultiChoiceClickListener() {//which:用户点击的条目的下标//isChecked:用户是选中该条目还是取消该条目
@Overridepublic void onClick(DialogInterface dialog, int which, booleanisChecked) {
checkedItems[which]=isChecked;
}
});//设置一个确定按钮
builder.setPositiveButton("确定", newOnClickListener() {
@Overridepublic void onClick(DialogInterface dialog, intwhich) {
String text= "";for(int i = 0; i < 4; i++){
text+= checkedItems[i]? items[i] + "," : "";
}
Toast.makeText(MainActivity.this, text, 0).show();
dialog.dismiss();
}
});
builder.show();
}
}