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

How to dynamically set background color in android app?

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

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

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

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

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

现在我正在尝试切换到颜色,而不是可绘制对象,我尝试过:

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 类型)不是可绘制类型!所以这段代码也不行。

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

textView.setTextColor(colorPickerColor);

colorPickerColor 是从颜色选择器首选项中检索到的 int 类型的变量

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

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

注意:我进行了搜索,但出现的每个结果要么不相关,要么无效。

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

mainLayout.setBackgroundDrawable(new ColorDrawable(colorPickerColor));

如果colorPickerColor是一个颜色资源id,

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

请注意,setBackgroundDrawable 方法已弃用,您可以改为调用 setBackground。