接上文
在Web开发中,HTML中有复选框CheckBox设置<input type="checkbox">,复选框用于在一组值中选择多个,比如个人爱好,可以从一组值中选择多个。而在Android中,对于复选框,可以使用CheckBox组件即可实现。
首先,我们看一下CheckBox的文档:

java.lang.Object
↳ android.view.View
↳ android.widget.TextView
↳ android.widget.Button
↳ android.widget.CompoundButton
↳ android.widget.CheckBox

我们前面说过了,CheckBox和RadioButton是直接继承自CompoundButton的,表示对复合式Button的一个抽象。下面我们从代码中来看看CheckBox的使用,在Eclipse中创建CheckBox的演示项目,编写代码如下:
    <TextView        android:id="@+id/favouriteLabel"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="请选择您的爱好" />    <CheckBox        android:id="@+id/swimming"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="游泳" />    <CheckBox        android:id="@+id/climbing"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="登山" />    <CheckBox        android:id="@+id/shopping"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="购物" />

一个用于提示信息的TextView组件就不多说了,后面跟着三个CheckBox组件,每个组件都设置了ID和长宽信息,最后都有一个显示的文本,那么基本的CheckBox组件就实现出来了,运行程序,我们可以看到如下效果:

和单选框一样,复选框也可以进行默认选中的配置,下面我们使用程序代码来演示:
package org.ourpioneer;import android.app.Activity;import android.os.Bundle;import android.widget.CheckBox;import android.widget.LinearLayout;public class CheckBoxDemoActivity extends Activity {private LinearLayout layout;private CheckBox gaming;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);super.setContentView(R.layout.main);layout = (LinearLayout) super.findViewById(R.id.layout);gaming = new CheckBox(this);gaming.setText("游戏");gaming.setChecked(true);layout.addView(gaming);}}

在编写代码之前,还是要为我们的布局管理器加上ID,以便在程序中进行操作。这里定义了两个成员变量,表示布局管理器和我们要添加的一个CheckBox组件。
首先,我们获取到布局管理器对象,使用findViewById()方法,很简单。下面是创建一个新的CheckBox组件,和其它视图组件一样,它的构造方法也是接受一个Context类型的对象,那么就是this。之后对这个CheckBox组件进行设置,显示文本为“游戏”,并且设置默认选中。最后将它加入到布局管理器中就可以了。
运行程序,我们可以看到如下效果:

我们在Activity程序中动态创建的CheckBox也显示出来了,并且已经被默认选中了。
Android中的Checkbox非常简单,示例代码请在附件中下载。
接下文

更多相关文章

  1. 垮平台开发平台
  2. Android(安卓)UI 之 获取组件或者元素的坐标
  3. 基于ActionbarActivity中Actionbar自定义布局
  4. Android(安卓)小游戏 2048
  5. Android(安卓)下拉刷新(刷新布局需用ScrollView包裹)
  6. 自定义圆形进度条
  7. android 登陆demo
  8. android 状态栏字体颜色设置 黑色 anctivity+dialog
  9. Android组件 文字标签(TextView)

随机推荐

  1. android实现图片模糊背景效果
  2. Android网络状态监听
  3. Android 通知栏Notification 悬浮通知栏
  4. android 版本及对应数值
  5. “Debug certificate expired” error
  6. Android如何导入已有的外部数据库
  7. Android连接到加密网络
  8. android子线程创建handler
  9. Android执行POST请求
  10. android Volley 使用