Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button android:id="@+id/but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示多选列表对话框"
android:layout_gravity="center_horizontal"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
Main.java
package com.example.multichoiceitems;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but=(Button) super.findViewById(R.id.but);
final TextView textView=(TextView) super.findViewById(R.id.textView);
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Builder b=new AlertDialog.Builder(MainActivity.this);
b.setIcon(R.drawable.ic_launcher);
b.setTitle("多选列表项");
/*
* 第一个参数表示颜色数组
* 第二个参数表示默认哪些项选中
* 第三个参数表示的是点击之后的监听事件
*/
b.setMultiChoiceItems(new String[]{"红色","绿色","蓝色"},new boolean[]{true,false,false}, new OnMultiChoiceClickListener(){
@Override
public void onClick(DialogInterface Dialgo, int which,
boolean isChecked) {
switch(which){
case 0:
if(isChecked){
textView.setText("选中了红色");
textView.setBackgroundColor(Color.RED);
}
break;
case 1:
if(isChecked){
textView.setText("选中了绿色");
textView.setBackgroundColor(Color.GREEN);
break;
}
case 2:
if(isChecked){
textView.setText("选中了蓝色");
textView.setBackgroundColor(Color.BLUE);
break;
}
}
}
});
b.setNegativeButton("确定", null);
b.create().show();
}
});
}
}