android中的CheckBox改变背景图片显示大小

发布于:2025-02-26 ⋅ 阅读:(17) ⋅ 点赞:(0)

在androidStudio的xml文件设置布局时,对于checkBox选中后,展示大小不同的背景图片

1.首先需要一个选择器存放背景图片,设置选中和未选中状态

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_hair1_cheek" android:state_checked="true" />
    <item android:drawable="@drawable/ic_hair1" />
</selector>

2.在布局文件中设置对应的checkBox,如果对应选中的图片大小不一样的时候,使用一下布局方式可以展示出对应的大小;

 <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/cl_hair_color"
            app:layout_constraintLeft_toRightOf="@+id/iv_hair_color"
            app:layout_constraintBottom_toBottomOf="@id/iv_hair_color"
            app:layout_constraintTop_toBottomOf="@+id/tv_hair_color"
            android:layout_width="wrap_content"
            android:layout_height="65dp">

            <androidx.appcompat.widget.AppCompatCheckBox
                android:id="@+id/cb_hair1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:background="@null"
                android:button="@drawable/selector_hair1"
                android:clickable="false"
                android:layout_width="54dp"
                android:layout_height="54dp"/>

            <androidx.appcompat.widget.AppCompatCheckBox
                android:id="@+id/cb_hair2"
                app:layout_constraintLeft_toRightOf="@+id/cb_hair1"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:background="@null"
                android:button="@drawable/selector_hair2"
                android:clickable="false"
                android:layout_marginLeft="15dp"
                android:layout_width="54dp"
                android:layout_height="54dp"/>

            <androidx.appcompat.widget.AppCompatCheckBox
                android:id="@+id/cb_hair3"
                app:layout_constraintLeft_toRightOf="@+id/cb_hair2"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:background="@null"
                android:button="@drawable/selector_hair3"
                android:clickable="false"
                android:layout_marginLeft="15dp"
                android:layout_width="54dp"
                android:layout_height="54dp"/>

        </androidx.constraintlayout.widget.ConstraintLayout>

主要实现时布局中的 

android:background="@null"
android:button="@drawable/selector_hair3"

如果将其反过来,则选中前后的图片大小都会保持不变

android:background="@drawable/selector_hair3"
android:button="@null"