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

   在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的演示项目,编写代码如下:
Xml代码   收藏代码
  1. <TextView  
  2.     android:id="@+id/favouriteLabel"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:text="请选择您的爱好" />  
  6. <CheckBox  
  7.     android:id="@+id/swimming"  
  8.     android:layout_width="fill_parent"  
  9.     android:layout_height="wrap_content"  
  10.     android:text="游泳" />  
  11. <CheckBox  
  12.     android:id="@+id/climbing"  
  13.     android:layout_width="fill_parent"  
  14.     android:layout_height="wrap_content"  
  15.     android:text="登山" />  
  16. <CheckBox  
  17.     android:id="@+id/shopping"  
  18.     android:layout_width="fill_parent"  
  19.     android:layout_height="wrap_content"  
  20.     android:text="购物" />  

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

    和单选框一样,复选框也可以进行默认选中的配置,下面我们使用程序代码来演示:
Java代码   收藏代码
  1. package org.ourpioneer;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4. import android.widget.CheckBox;  
  5. import android.widget.LinearLayout;  
  6. public class CheckBoxDemoActivity extends Activity {  
  7.     private LinearLayout layout;  
  8.     private CheckBox gaming;  
  9.     public void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         super.setContentView(R.layout.main);  
  12.         layout = (LinearLayout) super.findViewById(R.id.layout);  
  13.         gaming = new CheckBox(this);  
  14.         gaming.setText("游戏");  
  15.         gaming.setChecked(true);  
  16.         layout.addView(gaming);  
  17.     }  
  18. }  

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

    我们在Activity程序中动态创建的CheckBox也显示出来了,并且已经被默认选中了。
    Android中的Checkbox非常简单,示例代码请在附件中下载。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值