compoundButton(复合按钮)继承与Button,拥有Button的属性和方法。

compoundButton有:CheckBox , RadioButton,Switch。

compoundButton在Java代码中主要使用4中方法:

setChecked:设置按钮的勾选状态。

setButtonDrawable:设置左侧勾选图标的图形资源。

setOnCheckChangeListener:设置勾选状态变化的监视器。

isChecked:判断按钮是否勾选。

复选框CheckBox是CompoundButton一个最简单的实现控件,点击复选框将它勾选,再次点击取消勾 选。复选框对象调用setOnCheckedChangeListener方法设置勾选监听器,这样在勾选和取消勾选时就 会触发监听器的勾选事件。

案例:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:drawable="@drawable/check_choose"/>
    <item android:drawable="@drawable/check_unchoose"/>
</selector>
<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" />
    <CheckBox
        android:id="@+id/ck_custom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
<!--        改变左边的图标用button属性-->             android:button="@drawable/checkbox_selector4"
        android:checked="true"
        android:padding="5dp"
        android:text="这个CheckBox换了图标" />
</LinearLayout>
CheckBox ck_system = findViewById(R.id.ck_system);
CheckBox ck_custom = findViewById(R.id.ck_custom);
// ck_system,ck_custom设置了监听器,一旦出发就执行onCheckedChanged方法
ck_system.setOnCheckedChangeListener(this);
ck_custom.setOnCheckedChangeListener(this);
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    String desc = String.format("您%s了这个CheckBox",isChecked ? "勾选":"取消");
    buttonView.setText(desc);
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐