本节学习Diaolog。在生活中Dialog包括:三种样式(单选对话框,多选对话框,确定取消对话框)
那我们一个一个分析:
确定取消对话框:
public void click1(View v) { AlertDialog.Builder builder = new Builder(MainActivity.this); //设置图标 builder.setIcon(android.R.drawable.alert_light_frame); //设置标题 builder.setTitle("提示"); //设置正文 builder.setMessage("是否退出游戏?"); //设置确定按钮 builder.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { //确定后回调函数 Toast.makeText(MainActivity.this, "退出", Toast.LENGTH_SHORT).show(); } }); //设置取消按钮 builder.setNegativeButton("取消", new OnClickListener(){ @Override public void onClick(DialogInterface arg0, int arg1) { //取消后回调函数 Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show(); } }); //显示Dialog AlertDialog dialog = builder.create(); dialog.show(); }
显示效果:
单选对话框:
public void click2(View v) { AlertDialog.Builder builder = new Builder(MainActivity.this); builder.setTitle("请选择性别"); final String[] items = new String[]{ "男", "女" }; //-1代表的意思是: 默认那个都不选中,0代表男,1代表女 builder.setSingleChoiceItems(items, 1, new OnClickListener() { //which: 代表是选中那个选项 @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, items[which] +"被选中了!" , Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }); builder.show(); }
显示结果为:
多选对话框:
public void click3(View v) { AlertDialog.Builder builder = new Builder(MainActivity.this); builder.setTitle("请选择您喜欢的类型"); final String[] items = new String[]{ "温柔型", "性感型", "火辣型", "奶妈型", "萝莉型", }; //初始值:true代表选中,false代表不选中 final boolean[] checkedItems = new boolean[]{ true, true, false, true, true, }; builder.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener() { //which:用户点击的条目的下标 //isChecked:用户是选中该条目还是取消该条目 @Override public void onClick(DialogInterface arg0, int which, boolean isChecked) { checkedItems[which] = isChecked; } }); builder.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //封装显示 String text = ""; for(int i = 0; i < items.length; i++) { text += checkedItems[i] ? items[i] + ";" : ""; } Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }); builder.show(); }
显示效果:
关于Dialog就说到这里
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-04 21:39:21