如何以编程方式更改按钮颜色- Android

时间:2022-11-20 22:51:51

I have a button that I want to be round, so I made an xml file and set it as its background. The button is now round but I want to be able to change its color programmatically instead of hardcoding it into the xml file. How can I do this?

我有一个圆形的按钮,所以我创建了一个xml文件并将它设置为它的背景。按钮现在是圆形的,但是我希望能够以编程方式更改它的颜色,而不是硬编码到xml文件中。我该怎么做呢?

Here is my xml file for round button.

这是圆形按钮的xml文件。

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

3 个解决方案

#1


1  

Try this:

试试这个:

GradientDrawable backgroundShape = (GradientDrawable)btn.getBackground();
backgroundShape.setColor(Color.BLACK);

#2


9  

You can change color of view by using ColorFilter. It is very easy and quick.

您可以使用ColorFilter更改视图的颜色。它非常简单和快速。

button.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

This code will color button into red color.

此代码将按钮的颜色变为红色。

#3


1  

Try to get button background set color using getPaint :

尝试使用getPaint获得按钮背景设置颜色:

((ShapeDrawable)yourbutton.getBackground()).getPaint().setColor(getResources().getColor(R.color.colorToSet));

#1


1  

Try this:

试试这个:

GradientDrawable backgroundShape = (GradientDrawable)btn.getBackground();
backgroundShape.setColor(Color.BLACK);

#2


9  

You can change color of view by using ColorFilter. It is very easy and quick.

您可以使用ColorFilter更改视图的颜色。它非常简单和快速。

button.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

This code will color button into red color.

此代码将按钮的颜色变为红色。

#3


1  

Try to get button background set color using getPaint :

尝试使用getPaint获得按钮背景设置颜色:

((ShapeDrawable)yourbutton.getBackground()).getPaint().setColor(getResources().getColor(R.color.colorToSet));