以编程方式更改自定义按钮形状的颜色

Changing the color of a custom buttonshape programmatically

我有一个用于所有按钮的自定义按钮形状。我现在正在尝试实现主题,但我可以弄清楚如何在不删除自定义形状的情况下自动更改按钮的 "solid" 颜色。任何人都可以让我知道如何去做吗?我试图更改按钮的背景颜色,但没有看到任何变化;不知道为什么。

这是我的自定义按钮形状:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
    android:radius="14dp"
    />
<solid
    android:color="#D1D1D1"
    />
<size
    android:width="177dp"
    android:height="60dp"
    />
<stroke
    android:width="7dp"
    android:color="#FFFFFF"
    />
</shape>

我认为您应该为 xml 文件分配一个 ID

然后你就可以通过findViewById

来识别Button

如果您使用多个主题,您可以使用大小写切换功能

Button button= (Button)findViewById(R.id.yourbutton)

button.setBackgroundColor(getResources().getColor(R.color.whatevercolor));   //or even better button.setBackgroundColor(0xFFFFFF);