如何在Android应用程序中动态设置背景颜色?

时间:2017-02-14 02:19:36

标签: android android-layout colors background programmatically

现在试图解决这个问题一年了。很久以前有一个临时的解决方法,但是当我准备在我开发的应用程序中添加新功能时,问题又回来了。

主要目标:让用户能够选择几乎任何颜色作为应用程序的背景。

当前迭代:我有2个可绘制图像,一个绿色,一个蓝色。用户可以在两者之间切换,但只能通过:

if (bgColor) {
        getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.custom_blue_background_simple));
    }
    else {
        getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.custom_green_background));
    }
}

如果用户将背景从默认绿色更改为蓝色,则bgColor是布尔值。

现在我正在尝试切换到颜色,而不是drawable,我尝试过:

LayoutInflater layInflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layInflate.inflate(R.layout.main_activity_layout, null);
    mainLayout = (RelativeLayout) view.findViewById(R.id.mainActivityRelativeLayoutId);
    mainLayout.setBackgroundResource(R.color.colorRed);

但它没有做任何事情!

然后我尝试使用可绘制图像,但颜色(类型int)不是类型可绘制的!所以这段代码也不起作用。

困境和问题:我有一个颜色选择器设置/首选项。用户可以从中选择几乎任何颜色,并将其保存为int类型的颜色。 它成功地使用了文本颜色:

textView.setTextColor(colorPickerColor);

colorPickerColor是从颜色选择器首选项

中检索的int类型的变量

但是当尝试使用它来更改布局或视图的背景时,它什么都不做。即使设置常量/硬编码颜色也不会改变颜色(如上面的代码所示)。我能够用颜色改变背景的唯一方法是用户可绘制(现在为我工作,但效率极低,因为我必须为每种可选颜色设置单独的可绘制颜色,可能是数百万或数十亿),或者用于颜色的十六进制代码,但硬编码到布局的XML中,因为将它放在代码中什么也不做(完全没用,因为用户将无法选择)。

通过代码以编程方式/动态指定int类型的颜色来更改布局背景颜色的正确方法是什么?我的应用支持的最小API是14

注意:我已经搜索过了,但所有出现的结果要么没有关系,要么没有用。

1 个答案:

答案 0 :(得分:0)

ColorDrawable将是您案例的解决方案。假设colorPickerColor是要绘制的整数颜色代码,可以使用以下代码设置背景:

mainLayout.setBackgroundDrawable(new ColorDrawable(colorPickerColor));

如果colorPickerColor是颜色资源ID,

mainLayout.setBackgroundDrawable(new ColorDrawable(getResources().getColor(colorPickerColor)));

请注意,不推荐使用setBackgroundDrawable方法,而是可以调用setBackground。

相关问题