【问题标题】:How to dynamically set background color in android app?如何在android应用程序中动态设置背景颜色?
【发布时间】:2017-02-14 02:19:35
【问题描述】:

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

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

当前迭代:我有 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 类型)不是可绘制类型!所以这段代码也不起作用。

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

textView.setTextColor(colorPickerColor);

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

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

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

注意:我已经搜索过,但出现的每个结果要么不相关,要么不起作用。

【问题讨论】:

  • 你试过view.setBackgroundColor(int color)吗?用法示例:mainLayout.setBackgroundColor(0xFF000000);
  • @Isaac 说得对。记住前导 FF,使其完全不透明。
  • @isaac 这不会做任何事情。这不是我一直在做的吗?
  • @Aeon Psych 您想使用代码更改布局颜色吗?你有一个很长的描述你试过艾萨克所说的吗
  • @Charuක 是的,我有。它不会影响任何事情。好像和我之前发的差不多

标签: android android-layout colors background programmatically


【解决方案1】:

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

mainLayout.setBackgroundDrawable(new ColorDrawable(colorPickerColor));

如果 colorPickerColor 是颜色资源 id,

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

请注意 setBackgroundDrawable 方法已被弃用,您可以调用 setBackground 代替。

【讨论】:

  • 使用新的 ColorDrawable() 方法有效,但不是您发布的方式。我必须像使用可绘制图像一样使用它:getWindow().setBackgroundDrawable(new ColorDrawable(bgColorPicker));这是可以接受的,还是不好的形式?
  • @AeonPsych,没有好坏之分,这取决于你的情况。例如,如果您只想让用户选择一种颜色并应用于应用程序的每个活动,您可以只在基本活动中使用 getWindow() 设置它,所有活动都扩展至此。如果你想要更多的灵活性,例如,你可能在一个 Activity 中导航了多个 Fragment,那么你可以在一个 Fragment 的 mainLayout(例如可能是布局的根元素)中设置它,这样做,你的应用程序可以有不同的不同屏幕中的颜色。
  • 很奇怪,因为我不能只改变布局的颜色。 mainLayout.setBackgroundDrawable(new ColorDrawable(colorPickerColor));对我不起作用哈哈。出于某种原因,它仅在我为 getWindow() 更改它时才有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 2010-11-30
  • 2013-08-04
  • 2011-02-14
相关资源
最近更新 更多