xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox
android:id="@+id/cb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first"/>
<CheckBox
android:id="@+id/cb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="second"/>
<CheckBox
android:id="@+id/cb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="third"/>
<TextView
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
java对CheckBox的传值
package com.example.assembly;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity implements OnCheckedChangeListener {
private TextView showTv;
private String str = "";
private String str1 = "", str2 = "", str3 = "";
private CheckBox cb1, cb2, cb3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showTv = (TextView) findViewById(R.id.show);
cb1 = (CheckBox) findViewById(R.id.cb1);
cb2 = (CheckBox) findViewById(R.id.cb2);
cb3 = (CheckBox) findViewById(R.id.cb3);
cb1.setOnCheckedChangeListener(this);
cb2.setOnCheckedChangeListener(this);
cb3.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.cb1:
if (isChecked) {
str1 = "first,";
} else {
str1 = "";
}
break;
case R.id.cb2:
if (isChecked) {
str2 = "second,";
} else {
str2 = "";
}
break;
case R.id.cb3:
if (isChecked) {
str3 = "third,";
} else {
str3 = "";
}
break;
default:
break;
}
str = str1 + str2 + str3;
showTv.setText(str);
}
}
java对CheckBox设值
if (str.contains("first")) {
cb1.setChecked(true);
}else {
cb1.setChecked(false);
}
if (str.contains("second")) {
cb1.setChecked(true);
}else {
cb1.setChecked(false);
}
if (str.contains("third")) {
cb1.setChecked(true);
}else {
cb1.setChecked(false);
}