1,两种状态:选中状态(true),未选中状态(false)
2,重要属性:
android:checked="false"//当前CheckBox是否被选中,默认为false
3,layout布局中的代码:
<span style="font-size:18px;"><RelativeLayout 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" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请选择你的爱好:"
android:textSize="20sp">
</TextView>
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="30dp"
android:checked="false" //默认为false,可以省略不写
android:text="音乐" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/checkBox1"
android:layout_marginTop="39dp"
android:checked="false"
android:text="体育" />
</RelativeLayout></span>
4,java类中的代码:
<span style="font-size:18px;">public class MainActivity extends Activity {
private CheckBox checkBox1, checkBox2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化CheckBox控件
checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
// 设置监听事件
checkBox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
// 通过onCheckedChanged来监听当前的checkBox是否被选中
if (isChecked) {
String text = checkBox1.getText().toString();
// 在LogCat中打印输出选中的文本信息
Log.i("tag", text);
}
}
});
checkBox2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if (isChecked) {
String text = checkBox2.getText().toString();
Log.i("tag", text);
}
}
});
}
}</span>