发布时间:2025-12-11 00:51:29 浏览次数:1
在Android中,CompoundButton是一个继承自Button的抽象类,它实现了Checkable接口。CompoundButton具有两种状态:选中和未选中。它的常见子类有CheckBox和Switch。
CompoundButton的主要方法和用法如下:
isChecked():检查CompoundButton是否被选中。
setChecked(boolean checked):设置CompoundButton的选中状态。
setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener):设置CompoundButton的选中状态改变监听器。
下面是一个示例代码,演示如何使用CompoundButton:
// 在XML布局文件中定义一个CheckBox<CheckBoxandroid:id="@+id/checkbox"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Check me" />// 在Java代码中获取CheckBox实例并设置选中状态改变监听器CheckBox checkbox = findViewById(R.id.checkbox);checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {if (isChecked) {// 当CheckBox被选中时执行的代码} else {// 当CheckBox被取消选中时执行的代码}}});// 获取并检查CheckBox的选中状态boolean isChecked = checkbox.isChecked();通过使用CompoundButton的子类CheckBox或Switch,我们可以在用户界面中添加复选框或开关按钮,并根据选中状态执行相应的操作。