如何在 android 中显示带有图像的开关小部件?

How to display switch widget with image in android?

请帮助我在 android 中创建开关小部件,其中的图像可以随状态变化而变化。

应该是这样的:

使用如下。它是 this answer

的编辑版本
<Switch
    android:id="@+id/th"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:textColor="#000000"
    app:textOff="@string/switch_no"
    app:textOn="@string/switch_yes"
    app:thumb="@drawable/apptheme_switch_inner_holo_light"
    app:track="@drawable/apptheme_switch_track_holo_light" />

在 drawable 文件夹中,创建一个 xml 文件 my_btn_toggle.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false" android:drawable="@drawable/red"  />
    <item android:state_checked="true" android:drawable="@drawable/green"/>
</selector>

其中红色和绿色是您想要的图像。

并在定义切换按钮的 xml 部分添加:

android:background="@drawable/my_btn_toggle

希望对您有所帮助。