android widget 之CheckBox
CheckBox 是一种多选按钮,用户可以在一组选项中选择多个。CheckBox也是Android中最常用的组件。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text = "你希望能够做你的红颜知己的女人:"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<CheckBox android:text="杨贵妃" android:id="@+id/checkbox1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<CheckBox android:text="貂蝉" android:id="@+id/checkbox2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<CheckBox android:text="西施" android:id="@+id/checkbox3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<CheckBox android:text="王昭君" android:id="@+id/checkbox4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button android:id="@+id/btnGetCheckValue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="获取选择的值"/>
</LinearLayout>
CheckBox 通过isChecked方法来确定是否选中。
CheckBox 支持OnClickListener 以及OnCheckedChangeListener:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkbox);
final CheckBox cb1 = (CheckBox)findViewById(R.id.checkbox1);
final CheckBox cb2 = (CheckBox)findViewById(R.id.checkbox2);
final CheckBox cb3 = (CheckBox)findViewById(R.id.checkbox3);
final CheckBox cb4 = (CheckBox)findViewById(R.id.checkbox4);
final CheckBox[] cbs= new CheckBox[]{cb1,cb2,cb3,cb4};
Button btnGetCheckValue = (Button)findViewById(R.id.btnGetCheckValue);
btnGetCheckValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text = "你选择的红颜知己有:";
for(CheckBox cb : cbs){
if(cb.isChecked()){
text += cb.getText()+",";
}
}
setTitle(text);
}
});
for(final CheckBox cb: cbs){
cb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println(cb.getText());
}
});
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
setTitle("你选了" +cb.getText());
Toast.makeText(getApplicationContext(), "you selected "+buttonView.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
更多相关文章
- 在Android(安卓)Studio上进行OpenCV3.1开发环境的配置
- 快速下载 Android(安卓)framework 源码
- [原创] Android(安卓)SDK 安装全记录
- Android下使用Logcat打印信息
- Android添加单元测试的方法与步骤
- Android下使用Logcat打印信息
- 面向 x86 的 Android* 入门指南
- Android(安卓)Studio下载安装使用教程
- 【技术直通车】处理ArcGIS Android工程和ADT v17中的依赖