您的位置:首页 > 移动开发 > Android开发

Android控件笔记——CheckBox复选框

2016-05-13 00:00 585 查看
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控件,并对它进行相关设置:

[code=plain]<!--activity_main.xml-->
<CheckBox
android:checked="false"
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="你是猪" />


初始化CheckBox,并设置监听器监听他的状态,并根据对应状态输出提示信息:

[code=plain]
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、效果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: