Java .setBackgroundColor 带有十六进制颜色代码 AndroidStudio

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25837449/
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-08-11 01:15:29  来源:igfitidea点击:

.setBackgroundColor with Hex Color Codes AndroidStudio

javaandroidandroid-studio

提问by Linus

View targetView;
targetView = (View)findViewById(R.id.mainlayout);

this works but

这有效,但

targetView.setBackgroundColor(Color.parseColor("#FFFFFF"));

and also this didn't work

而且这也不起作用

targetView.setBackgroundColor(Color.pasrsehexString("#FFFFFF"));

Error: Cannot resolve method'parseColor(java.lang.String)'

错误:无法解析方法'parseColor(java.lang.String)'

and : Cannot resolve method'pasrsehexString(java.lang.String)'

和:无法解析方法'parsehexString(java.lang.String)'

Pleas can somebodey help me and by the way i'm using Android Studio.

恳求有人可以帮助我,顺便说一句,我正在使用 Android Studio。

采纳答案by Tom

There are two main classes for color handling in Java/Android.

Java/Android 中有两个主要的颜色处理类。

This first one is from "plain" Java and can be found in java.awt.Color. This class supports converting a String into a color with the method decode. Example:

第一个来自“普通”Java,可以在java.awt.Color. 此类支持使用decode方法将 String 转换为颜色。例子:

Color red = Color.decode("#FF0000");

The second class is for Android and can be found in android.graphics.Color. The conversion can be done with the method parseColor.

第二个类是针对 Android 的,可以在android.graphics.Color. 可以使用parseColor方法完成转换。

int red = Color.parseColor("#FF0000");

So you should check which kind of Colorclass you've imported to your project. I recommend using the Android version of Color for your case. If you've done that the statement targetView.setBackgroundColor(Color.parseColor("#FFFFFF"));should work.

因此,您应该检查Color您已将哪种类导入到您的项目中。我建议您使用 Android 版本的 Color 来处理您的情况。如果您已经这样做了,那么该语句targetView.setBackgroundColor(Color.parseColor("#FFFFFF"));应该可以工作。

回答by FreshD

Define your color in the resource File color.xml

在资源文件 color.xml 中定义您的颜色

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="yourColor">#FFFFFF</color>
</resources>

and set Backgroundcolor

并设置背景色

targetView.setBackgroundResource(R.color.yourColor)  

This may be helpful: Color.xml

这可能会有所帮助:Color.xml

回答by laalto

No need to parse string colors in your code.

无需在代码中解析字符串颜色。

If you want to hardcode color values in your code (and not use color resources as in FreshD's answer), you can use intliterals for it. For example:

如果您想在代码中硬编码颜色值(而不是像 FreshD 的答案那样使用颜色资源),您可以使用int文字。例如:

targetView.setBackgroundColor(0xffffffff);

where the color is in ARGB.

颜色在 ARGB 中。