Android学习笔记八:基本视图组件:CheckBox

[url=http://sarin.iteye.com/blog/1636484]接上文[/url]
在Web开发中,HTML中有复选框CheckBox设置<input type="checkbox">,复选框用于在一组值中选择多个,比如个人爱好,可以从一组值中选择多个。而在Android中,对于复选框,可以使用CheckBox组件即可实现。
首先,我们看一下CheckBox的文档:
[img]http://dl.iteye.com/upload/attachment/0072/9971/6048e2ac-0522-392d-be40-1bc0e47ad80b.jpg[/img]
[b]java.lang.Object
↳ android.view.View
↳ android.widget.TextView
↳ android.widget.Button
↳ android.widget.CompoundButton
↳ android.widget.CheckBox[/b]
我们前面说过了,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组件就实现出来了,运行程序,我们可以看到如下效果:
[img]http://dl.iteye.com/upload/attachment/0072/9973/5bd9e2c9-eeca-33ca-9df1-91ee3fb810e0.jpg[/img]
和单选框一样,复选框也可以进行默认选中的配置,下面我们使用程序代码来演示:

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组件进行设置,显示文本为“游戏”,并且设置默认选中。最后将它加入到布局管理器中就可以了。
运行程序,我们可以看到如下效果:
[img]http://dl.iteye.com/upload/attachment/0072/9975/83c2622b-5faa-3b06-987c-b1b606a6432e.jpg[/img]
我们在Activity程序中动态创建的CheckBox也显示出来了,并且已经被默认选中了。
Android中的Checkbox非常简单,示例代码请在附件中下载。
[url=http://sarin.iteye.com/blog/1669773]接下文[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值