1、activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="多项选择列表框" />
</LinearLayout>
2、MainActivity.java类的实现
包
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
类的实现
public class MainActivity extends Activity {
private Button btn1;
ArrayList<Integer>MultiChoiceID = new ArrayList<Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String [] nItems = {"item1","item2","item3","item4","item5","item6"};
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
MultiChoiceID.clear();
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("多项选择");
// 设置多选项
builder.setMultiChoiceItems(nItems,
new boolean[]{false,false,false,false,false,false},
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
if (arg2) {
MultiChoiceID.add(arg1);
String tip = "你选择的ID为"+arg1+",值为"+nItems[arg1];
Toast toast = Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT);
toast.show();
}
else {
MultiChoiceID.remove(arg1);
}
}
});
// 设置确定按钮
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
String str = "";
int size = MultiChoiceID.size();
for(int i = 0; i < size; i++) {
str += (nItems[MultiChoiceID.get(i)]+",");
}
Toast toast = Toast.makeText(getApplicationContext(), "你选择了"+str, Toast.LENGTH_LONG);
toast.show();
}
});
// 设置取消按钮
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
});
}
}
3、效果图