每个多选框都是独立的,可以通过迭代所有多选框,然后根据其状态是否被选中再获取其值。
界面设计:
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<CheckBoxandroid:id="@+id/checkboxjava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="java" />
<CheckBoxandroid:id="@+id/checkboxdotNet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dotNet" />
<CheckBoxandroid:id="@+id/checkboxphp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PHP" />
<Button android:id="@+id/checkboxButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="获取值" />
</LinearLayout>
代码处理:
public class CheckBoxActivity extends Activity {
private static final String TAG ="CheckBoxActivity";
private List<CheckBox> checkboxs = newArrayList<CheckBox>();
@Override
public voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkbox);
checkboxs.add((CheckBox) findViewById(R.id.checkboxdotNet));
checkboxs.add((CheckBox) findViewById(R.id.checkboxjava));
checkboxs.add((CheckBox) findViewById(R.id.checkboxphp));
checkboxs.get(1).setChecked(true);//设置成选中状态
for(CheckBoxbox : checkboxs){
box.setOnCheckedChangeListener(listener);
}
Buttonbutton = (Button)findViewById(R.id.checkboxButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public voidonClick(View v) {
List<String> values = newArrayList<String>();
for(CheckBox box : checkboxs){
if(box.isChecked()){
values.add(box.getText().toString());
}
}
Toast.makeText(CheckBoxActivity.this,values.toString(), 1).show();
}
});
}
CompoundButton.OnCheckedChangeListener listener = newCompoundButton.OnCheckedChangeListener() { @Override
public voidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox checkBox= (CheckBox) buttonView;
Log.i(TAG,"isChecked="+ isChecked +",value="+ checkBox.getText());//输出单选框的值
}
};
}