Kotlin:如何更改切换按钮的背景颜色?

Kotlin: How to change background color of the toggle button?

我希望改变切换按钮的背景。 有两种方法,在 xml 和代码中,我认为..

我这样使用xml,成功了;

<ToggleButton
            android:id="@+id/downloadButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textOff="Download"
            android:textOn="Downloaded"
            android:background="@drawable/toggle_bg_sector"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

toggle_bg_sector.xml

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

toggle_download.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/blue" />
</shape>

toggle_downloaded.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/gray" />
</shape>

效果很好.. 但是,我想知道以编程方式进行。

我在 onCreate 中做了这个。

downloadButton.setOnCheckedChangeListener { _: CompoundButton?, isChecked ->
            if (isChecked)
                downloadButton.setBackground(R.drawable.toggle_download)
            else
                downloadButton.setBackground(R.drawable.toggle_downloaded)
        }

但是,我在 R.drawable.toggle_download 上收到错误消息。

谁能解释一下?

您还可以像这样更改 MainActivity 中的颜色

downloadButton.setOnCheckedChangeListener { _: CompoundButton?, isChecked ->
        if (isChecked)
            downloadButton.setBackground(R.drawable.red)
        else
             downloadButton.setBackground(R.drawable.blue)
    }

通过这种方式,您可以轻松更改切换按钮的背景颜色