1.在目录res/values下array.xml中添加一个checkbox资源组:
- Android
- IOS
- Windows Phone
2.定义一个布局文件checkbox_dialog.xml:
3.定义java文件:
package com.test;import javax.security.auth.PrivateCredentialPermission;import android.app.Activity;import android.app.AlertDialog.Builder;import android.app.Dialog;import android.content.DialogInterface;import android.content.DialogInterface.OnMultiChoiceClickListener;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class CheckBoxDialog extends Activity { private TextView textView ; private Button button; //复选框初始状态都是未选中 boolean [] state =new boolean[]{false,false,false}; String[] contents=null; private final static int FLAG=1; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.checkbox_dialog); contents=getResources().getStringArray(R.array.array_checkbox); textView =(TextView)findViewById(R.id.textview); button = (Button)findViewById(R.id.button); button.setOnClickListener(clickListener); } private OnClickListener clickListener =new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // 显示对话框 showDialog(FLAG); } }; /** * 创建复选框对话框 */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog=null; switch (id) { case FLAG: Builder builder=new android.app.AlertDialog.Builder(this); //设置对话框的图标 builder.setIcon(R.drawable.header); //设置对话框的标题 builder.setTitle("复选框对话框"); builder.setMultiChoiceItems(R.array.array_checkbox, state, onMultiChoiceClickListener); //添加一个确定按钮 builder.setPositiveButton("OK", clickListener2); //创建一个复选框对话框 dialog=builder.create(); break; } return dialog; } private OnMultiChoiceClickListener onMultiChoiceClickListener =new OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { state[which]=isChecked; String result = "You checked:"; for (int i = 0; i < state.length; i++) { if(state[i]){ result=result+contents[i]+"、"; } } textView.setText(result.substring(0, result.length()-1)); } }; private android.content.DialogInterface.OnClickListener clickListener2 =new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } };}
4:显示效果图: