java 安卓。从代码更改 FrameLayout 的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13948526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:32:25  来源:igfitidea点击:

Android. Change the background color of a FrameLayout from code

javaandroidxmluser-interface

提问by Vlad Spreys

I'm trying to change the background color of a FramyLayout. The color is changing, but to the wrong one.

我正在尝试更改 FramyLayout 的背景颜色。颜色在变,但换错了。

However it is working fine if I do it through the XML.

但是,如果我通过 XML 进行操作,它就可以正常工作。

Here is my res/values/colors.xml code

这是我的 res/values/colors.xml 代码

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="grey">#888888</color>
    <color name="white">#FFFFFF</color>
    <color name="red">#ffff3448</color>
    <color name="green">#ff408c3a</color>
</resources>

Here is how it looks like if I make changes in the XML Colors changed correctly

这是我在 XML 中进行更改时的样子 颜色更改正确

And that's what is happening if I try to do it with the code

如果我尝试用代码来做这件事,那就是正在发生的事情

 FrameLayout frameLayoutBalance = (FrameLayout)view.findViewById(R.id.frameLayoutBalance);
 frameLayoutBalance.setBackgroundColor(R.color.green);

Colors changed incorrectly

颜色改变不正确

回答by Vivek Khandelwal

You should not use frameLayoutBalance.setBackgroundColor(R.color.green);

你不应该使用 frameLayoutBalance.setBackgroundColor(R.color.green);

setBackgroundColor required a Color (i.e. its value as describe by Chirag Raval) not a color resources.

setBackgroundColor 需要颜色(即 Chirag Raval 描述的值)而不是颜色资源。

use this frameLayoutBalance.setBackgroundColor(getResources().getColor(R.color.green));

使用这个 frameLayoutBalance.setBackgroundColor(getResources().getColor(R.color.green));

回答by User

Use this code frameLayoutBalance.setBackgroundColor(Color.parseColor("#00aacc"));

使用此代码 frameLayoutBalance.setBackgroundColor(Color.parseColor("#00aacc"));