更改多个视图背景颜色

时间:2015-04-21 13:37:00

标签: android background-color

我有很多观点使用同一种颜色作为背景。我想以编程方式从服务器接收调用时更改所有视图的颜色。我不想打电话给每个观点

view.setBackgroundColor(new color);

有没有办法更改colors.xml中的颜色代码。

3 个答案:

答案 0 :(得分:2)

您无法替换xml文件中的颜色值。 但是你 可以创建在您的应用程序中使用的不同主题 动态更改主题

参见本教程:

http://www.developer.com/ws/android/changing-your-android-apps-theme-dynamically.html

答案 1 :(得分:1)

简短回答:不,你不能。资源在编译时定义。

针对类似案例,请参阅此问题:How can I programmatically change the value of a color in colors.xml?

答案 2 :(得分:0)

我最终要做的是创建一个自定义类来设置颜色形式首选项。并且我想在任何地方使用这个类来改变颜色。下次绘制视图时,它会获得新颜色。像这样:

public class ColoredToolbar extends android.support.v7.widget.Toolbar {

public ColoredToolbar(Context context) {
    super(context);
    setBackgroundColor(context);
}

public ColoredToolbar(Context context, AttributeSet attrs) {
    super(context, attrs);
    setBackgroundColor(context);
}

public ColoredToolbar(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setBackgroundColor(context);
}

private void setBackgroundColor(Context context) {
    int color = PreferenceHelper.getToolBarColor(context, Preferences.PREF_TITLE_BAR_COLOR_KEY);
    this.setBackgroundColor(color);
}

}

相关问题