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();

}

}

});

}

}

更多相关文章

  1. 在Android(安卓)Studio上进行OpenCV3.1开发环境的配置
  2. 快速下载 Android(安卓)framework 源码
  3. [原创] Android(安卓)SDK 安装全记录
  4. Android下使用Logcat打印信息
  5. Android添加单元测试的方法与步骤
  6. Android下使用Logcat打印信息
  7. 面向 x86 的 Android* 入门指南
  8. Android(安卓)Studio下载安装使用教程
  9. 【技术直通车】处理ArcGIS Android工程和ADT v17中的依赖

随机推荐

  1. Android(安卓)studio怎样隐藏标题栏
  2. Android(安卓)轻松实现语音识别的完整代
  3. 【Android】配置文件属性说明
  4. 【Android基础】Android开发学习笔记
  5. Android中attr自定义标签详解
  6. ant编译android工程用批处理打包
  7. Android声音播放实例代码
  8. android 设置布局为无标题样式
  9. android 通过 button 弹出menu
  10. android-passwordsafe - Android(安卓)Pa