2023年3月8日(软件工程日报)
在Android体系中,CompoundButton类是抽象的,复合按钮,因为是抽象类,所以它不能直接使用。实际开发中用的是CompoundButton的几个派生类,主要有复选框CheckBox、单选按钮RadioButton以及开关按钮Switch,这些派生类均可使用CompoundButton的属性和方法。加之CompoundButton本身继承了Button类
CompoundButton在XML文件中主要使用下面两个属性。
checked:指定按钮的勾选状态,true表示勾选,false则表示未勾选。默认为未勾选。
button:指定左侧勾选图标的图形资源,如果不指定就使用系统的默认图标。
CompoundButton在Java代码中主要使用下列4种方法。
setChecked:设置按钮的勾选状态。
setButtonDrawable:设置左侧勾选图标的图形资源。
setOnCheckedChangeListener:设置勾选状态变化的监听器。
isChecked:判断按钮是否勾选。
View Code
View Code
View Code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp" > <CheckBox android:id="@+id/ck_system" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" android:checked="false" android:text="这是系统的CheckBox" android:textColor="@color/black" android:textSize="17sp" /> </LinearLayout>

public class CheckBoxActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_check_box); CheckBox ck_system = findViewById(R.id.ck_system); CheckBox ck_custom = findViewById(R.id.ck_custom); ck_system.setOnCheckedChangeListener(this); ck_custom.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { String desc = String.format("您%s了这个CheckBox", isChecked ? "勾选" : "取 消勾选"); buttonView.setText(desc); } }
Switch是开关按钮,它像一个高级版本的CheckBox,在选中与取消选中时可展现的界面元素比复选框丰
富。Switch控件新添加的XML属性说明如下:
textOn:设置右侧开启时的文本。
textOff:设置左侧关闭时的文本。
track:设置开关轨道的背景。
thumb:设置开关标识的图标。

<CheckBox android:id="@+id/ck_status" android:layout_width="60dp" android:layout_height="30dp" android:background="@drawable/switch_selector" android:button="@null" /> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/switch_on"/> <item android:drawable="@drawable/switch_off"/> </selector>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南