学Android---CheckBox

本文详细介绍了Android开发中常用的控件CheckBox,包括其定义、基本使用方法及代码实现过程。通过示例展示了如何创建CheckBox,并为其添加点击监听事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天就复习一下简单的CheckBox吧~~

1、什么是CheckBox:
CheckBox即是我们常见的复选框,它有两种状态,选中为true,未选中为false。常见的应用是多项选择,比如在选择兴趣爱好时,可以选中多个选项。

2、效果图。如下图所示
启动时的效果,三个选项的checked属性都默认为false
–>
选中了一个选项后

3、CheckBox的常用属性:
android:checked=”false”

4、代码实现:
(1)在布局文件中添加CheckBox并设置有关属性

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:checked="false"
        android:text="篮球"
        android:textSize="20sp" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="足球"
        android:textSize="20sp" />


    <CheckBox
        android:id="@+id/checkBox3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="羽毛球"
        android:textSize="20sp" />

(2)回到MainActivity添加逻辑代码,完整代码如下:

public class MainActivity extends Activity implements OnCheckedChangeListener{

    private CheckBox checkBox1;
    private CheckBox checkBox2;
    private CheckBox checkBox3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化checkBox
        checkBox1 = (CheckBox)findViewById(R.id.checkBox1);
        checkBox2 = (CheckBox)findViewById(R.id.checkBox2);
        checkBox3 = (CheckBox)findViewById(R.id.checkBox3);

        //通过设置checkBox的监听事件来对checkBox处理,判断其是否被选中
        //需要注意的是,CheckBox的监听事件与ToggleButton一样是onCheckedChangeListener而不是onClickListener
        checkBox1.setOnCheckedChangeListener(this);
        checkBox2.setOnCheckedChangeListener(this);
        checkBox3.setOnCheckedChangeListener(this);
    }

   /*
    *buttonView---指被选中的控件
    *isChecked---指控件的状态
    */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // 首先判断是否被选中
        if(isChecked){
            //获得checkBox的文本内容并用Toast打出来 
            String text = buttonView.getText().toString();
            Toast.makeText(MainActivity.this, "你选择了"+text, Toast.LENGTH_SHORT).show();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值