1、CheckBox的两种状态:
选中状态(true),未选中状态(false);
2、属性:
android:id="@+id/checkbox"
android:layout_width="warp_content"
android:layout_height="warp_content"
android:checked="false"
android:text="男"
3、应用:
拖入CheckBox控件,并对它进行相关设置:
<!--activity_main.xml-->
<CheckBox
android:checked="false"
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="你是猪" />
初始化CheckBox,并设置监听器监听他的状态,并根据对应状态输出提示信息:
public class MainActivity extends Activity {
//定义checkBox
private CheckBox checkBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化checkBox
checkBox=(CheckBox) findViewById(R.id.checkBox1);
//通过设置checkBox的监听事件来对checkBox是不是被选中
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//通过匿名内部类来实现监听器
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
//通过onCheckChanged来监听当前的checkBox是否被选中
if(arg1){
//获得checkBox的文本内容
String text="对!"+checkBox.getText().toString();
Toast.makeText(MainActivity.this, text, 1).show();
}
else{
Toast.makeText(MainActivity.this, "不对,你是猪!", 1).show();
}
}
});
}
}
4、效果: