简体   繁体   English

以编程方式更改可绘制xml文件中的颜色

[英]Programmatically change colors in drawable xml file

I need to change my application's colors during runtime. 我需要在运行时更改应用程序的颜色。 I parse data file to get colors and I save it in class with static fields and methods: 我解析数据文件以获取颜色,并将其保存在具有静态字段和方法的类中:

public class Colors {

    private static String colorOneBackground = "#00577F";
    private static String colorOneForeground = "#FFFFFF";

    public static void setColorOneBackground(String colorOneBackground) {
        Colors.colorOneBackground = colorOneBackground;
    }

    public static int getColorOneForeground() {
        return Color.parseColor(colorOneForeground);
    }
    // more colors...

Then, for example when I want to change the background of screen I do it so: 然后,例如,当我想更改屏幕背景时,可以这样做:

RelativeLayout relativeLayout = (RelativeLayout) myView.findViewById(R.id.loginBackground);
        relativeLayout.setBackgroundColor(Colors.getColorOneBackground());

Same with textviews and other widgets. 与textviews和其他小部件相同。 However, I have encountered one problem. 但是,我遇到了一个问题。 Some styles are defined in Drawable folder, for example, mybutton.xml: 在Drawable文件夹中定义了一些样式,例如mybutton.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android=" http://schemas.android.com/apk/res/android "
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFFFF"
        android:centerColor="#FFFFFF"
        android:endColor="#FFFFFF"
        android:angle="270" />
    <corners android:radius="5dp" />
    <stroke android:width="3px" android:color="#000000" />
</shape>

And I set this as my button's background: 我将其设置为按钮的背景:

<Button  
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:id="@+id/title"
   android:background="@drawable/mybutton" />

As I said I want to change these color values programatically. 如我所说,我想以编程方式更改这些颜色值。 So I want to know if it is possible to dinamically change color values defined in xml file? 所以我想知道是否有可能改变xml文件中定义的颜色值?

try this : to change color in your drawable xml file: 尝试以下操作:更改可绘制xml文件中的颜色:

button.setBackgroundResource(R.drawable.mybutton);  //drawable id
GradientDrawable gd = (GradientDrawable) button.getBackground().getCurrent();
gd.setColor(Color.parseColor("#000000")); //set color
gd.setStroke(2, Color.parseColor("#00FFFF"), 5, 6);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM