import android.app.Activity; import android.app.AlertDialog; 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.ListView; public class MainActivity extends Activity implements OnClickListener { private String[] province = new String[] { "上海", "北京", "湖南", "湖北", "海南" }; private Button btnMultiChoice; private ListView lv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnMultiChoice = (Button) findViewById(R.id.btnMultiChoice); btnMultiChoice.setOnClickListener(this); } @Override public void onClick(View v) { showMultiChoiceItems(); } private void showMultiChoiceItems() { AlertDialog builder = new AlertDialog.Builder(this) .setTitle("请选择你的省份:") .setMultiChoiceItems(province, new boolean[] { false, false, false, false, false }, new OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { // TODO Auto-generated method stub } }) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String s = "您选择了:"; // 扫描所有的列表项,如果当前列表项被选中,将列表项的文本追加到s变量中。 for (int i = 0; i < province.length; i++) { if (lv.getCheckedItemPositions().get(i)) { s += i + ":" + lv.getAdapter().getItem(i) + " "; } } // 用户至少选择了一个列表项 if (lv.getCheckedItemPositions().size() > 0) { new AlertDialog.Builder(MainActivity.this) .setMessage(s).show(); System.out.println(lv.getCheckedItemPositions() .size()); } // 用户未选择任何列表项 else if (lv.getCheckedItemPositions().size() <= 0) { new AlertDialog.Builder(MainActivity.this) .setMessage("您未选择任何省份").show(); } } }).setNegativeButton("取消", null).create(); lv = builder.getListView(); builder.show(); } }