我需要在运行时更改应用程序的颜色。我解析数据文件以获取颜色,并使用静态字段和方法将其保存在类中:
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...
然后,例如,当我想要改变屏幕的背景时,我这样做:
RelativeLayout relativeLayout = (RelativeLayout) myView.findViewById(R.id.loginBackground);
relativeLayout.setBackgroundColor(Colors.getColorOneBackground());
与textviews和其他小部件相同。但是,我遇到了一个问题。某些样式在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>
我将此设为我按钮的背景:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/title"
android:background="@drawable/mybutton" />
正如我所说,我想以编程方式更改这些颜色值。所以我想知道是否有可能以动态方式更改xml文件中定义的颜色值?
答案 0 :(得分:3)
试试这个:改变drawable 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);