Android学习(31) --对话框&单选对话框&多选对话框

对话框

	AlertDialog.Builder builder = new Builder(this);
		//设置图标
		builder.setIcon(android.R.drawable.alert_dark_frame);
		//设置标题
		builder.setTitle("删除提示");
		//设置文本
		builder.setMessage("确定删除么");
		
		//设置确定按钮
		builder.setPositiveButton("确定", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(MainActivity.this, "确定", 0).show();
			}
		});
		
		//设置取消按钮
		builder.setNegativeButton("取消", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(MainActivity.this, "<span style="font-family: Arial, Helvetica, sans-serif;">取消</span>", 0).show();
			}
		});
		//使用创建器,生成一个对话框对象
		AlertDialog ad = builder.create();
		ad.show();


单选对话框

		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("请选择性别");
		final String[] items = new String[]{
				"男",
				"女"
		};
		
		builder.setSingleChoiceItems(items, -1, new OnClickListener() {
			
			//which:用户所选的条目的下标
			//dialog:触发这个方法的对话框
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(MainActivity.this, "您选择的是:" + items[which], 0).show();
				//关闭对话框
				dialog.dismiss();
			}
		});
		builder.show();


多选对话框

		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("请选择您觉得帅的人");
		final String[] items = new String[]{
				"小小1",
				"小小2",
				"小小3",
				"小小4"
		};
		final boolean[] checkedItems = new boolean[]{
				true,
				true,
				false,
				false
				
		};
		
		builder.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener() {
			
			//which:用户点击的条目的下标
			//isChecked:用户是选中该条目还是取消该条目
			@Override
			public void onClick(DialogInterface dialog, 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 < 4; i++){
					text += checkedItems[i]? items[i] + "," : "";
				}
				Toast.makeText(MainActivity.this, text, 0).show();
				dialog.dismiss();
			}
		});
		builder.show();


你可能感兴趣的:(Android学习(31) --对话框&单选对话框&多选对话框)