如何在 kotlin 中将按钮的背景资源从一个自定义可绘制对象设置为另一个自定义可绘制对象?

How to set the background resource of a button from one custom drawable to another custom drawable in kotlin?

我在 Android 中有一组按钮,它们都使用相同的自定义可绘制对象作为背景,按下按钮时,我希望用于背景的可绘制对象更改为不同的自定义绘图。我用来执行此操作的代码如下:

selectedButton.setBackgroundResource(R.drawable.roundedbuttongreen) // Change the background resource to the roundedbuttongreen drawable

名为 roundedbuttongreen.xml 的自定义绘图的 XML 是:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="10dp">
    <solid android:color="#4CAD71"/> <!-- this one is ths color of the Rounded Button -->
    <corners
            android:bottomLeftRadius="50dp"
            android:bottomRightRadius="50dp"
            android:topLeftRadius="50dp"
            android:topRightRadius="50dp"/>
</shape> 

出现的问题是按钮的颜色发生了变化,但没有变成正确的颜色,而是变成了灰色,应该是绿色。截图如下:

image of the button after the background resource has been changed, it should be green

如果有人能告诉我我做错了什么,那就太好了

我建议您像这样在自定义形状上添加选中状态,然后将此形状添加为按钮的背景。

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

希望对你有用。

我查看了我的 xml 布局代码,特别是我的按钮,问题是按钮 backgroundTint 属性 的值是灰色的,结果当我试图改变可绘制的背景,按钮的颜色总是灰色的。

为了解决这个问题,我将背景色调的值更改为绿色,问题就解决了