Android学习笔记之CheckBox

本文介绍了Android中CheckBox控件的使用方法。通过一个示例应用程序详细展示了如何在布局文件中定义CheckBox,并通过Java代码为其设置监听器,实现对选中状态变化的响应。

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

CheckBox复选按钮是一种有双状态按钮的特殊类型,可以选中或者不选中。可以现在布局文件中定义多选按钮,然后对每一个多选按钮进行事件监setOnCheckedChangeListener,通过isChecked来判断选项是否被选中

main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/theme" /> <CheckBox android:id="@+id/apple" android:text="@string/apple" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <CheckBox android:id="@+id/banana" android:text="@string/banana" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>


RadioGroupActivity.java

package Android.Activity; import android.app.Activity; import android.os.Bundle; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Toast; public class RadioGroupActivity extends Activity { /** Called when the activity is first created. */ private CheckBox appleCheck = null; private CheckBox bananaCheck = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //通过控件的ID来得到代表控件的对象 appleCheck = (CheckBox)findViewById(R.id.apple); bananaCheck = (CheckBox)findViewById(R.id.banana); //为RadioGroup设置监听器,需要注意的是,这里的监听器和Button控件的监听器有所不同 appleCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if(isChecked){ Toast.makeText(RadioGroupActivity.this,"恭喜你,还剩很多苹果", Toast.LENGTH_LONG).show(); } } }); bananaCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if(isChecked){ Toast.makeText(RadioGroupActivity.this,"恭喜你,还剩很多香蕉", Toast.LENGTH_LONG).show(); } } }); } }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值