Android中AlertDialog内含单选框或者复选框


主要代码如下:

创建代码:

/***
	 * 显示提示对话框
	 * 
	 * @param ctx
	 * @param Title
	 *            标题
	 * @param MSsg
	 *            内容
	 * @param OKText
	 *            确认按钮文字
	 * @param OKListener
	 *            确认按钮事件处理
	 * @param CancelText
	 *            取消按钮文字
	 * @param CancelListener
	 *            取消按钮文字处理
	 */
	public static void Alert(Context context, String Title, String MSsg,
			String OKText, OnClickListener OKListener, String CancelText,
			OnClickListener CancelListener, CharSequence[] items,
			boolean[] checkedItems, OnMultiChoiceClickListener listener,
			CharSequence[] sing_items, int checkedItem,
			DialogInterface.OnClickListener singLis) {
		AlertDialog.Builder alert = new AlertDialog.Builder(context);
		if (Title != null) {
			alert.setTitle(Title);
		}
		if (MSsg != null) {
			alert.setMessage(MSsg);
		}
		if (OKListener != null) {
			if (OKText != null) {
				alert.setPositiveButton(OKText, OKListener);
			}
		}
		if (CancelListener != null) {
			if (CancelText != null) {
				CancelText = "取消";
				alert.setNegativeButton(CancelText, CancelListener);
				alert.setCancelable(false);
			}
		}
		if (listener != null) {
			alert.setMultiChoiceItems(items, checkedItems, listener);
		}
		if (singLis != null) {
			alert.setSingleChoiceItems(sing_items, checkedItem, singLis);
		}

		alert.create().show();
	}


调用代码:

@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.chooseDateFormat:
			// Comman.Alert(MainActivity.this, "选择日期格式", null, null, null, "取消",
			// this, null, null, null, items, 1, this);
			Comman.Alert(MainActivity.this, "选择日期格式", null, null, null, "确定",
					this, items, checkedItems, this, null, -1, null);
			break;

		default:
			break;
		}
	}


重点代码:

复选框

private CharSequence[] items = { "05-15-2013", "2013-05-15", "15-05-2013" };
	private boolean[] checkedItems = { false, false, false };
	@Override
	public void onClick(DialogInterface dialog, int position, boolean isChecked) {
		checkedItems[position] = isChecked;
		String result = "您选择了:";
		for (int i = 0; i < checkedItems.length; i++) {
			if (checkedItems[i]) {
				result = result + items[i] + ",";
			}
		}
		chooseDateFormat.setText(result);
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		dialog.dismiss();
		// String text = "选择日期格式";
		// chooseDateFormat.setText(text + items[which]);
	}


单选框:

private CharSequence[] items = { "05-15-2013", "2013-05-15", "15-05-2013" };
	private boolean[] checkedItems = { false, false, false };
	@Override
	public void onClick(DialogInterface dialog, int which) {
		dialog.dismiss();
		String text = "选择日期格式";
		 chooseDateFormat.setText(text + items[which]);
	}


注意:

public class MainActivity extends Activity implements OnClickListener,
		OnMultiChoiceClickListener,
		android.content.DialogInterface.OnClickListener {

图片如下:


Android中AlertDialog内含单选框或者复选框_第1张图片

 

 

 

你可能感兴趣的:(Android)