Java 设置背景颜色:Android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18033260/
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
set background color: Android
提问by Cj1m
How Do I set the background color of my android app. When I try:
如何设置我的 android 应用程序的背景颜色。当我尝试:
LinearLayout li=(LinearLayout)findViewById(R.id.myLayout);
li.setBackgroundColor(Color.parseColor("#rrggbb"));
My app always crashes. Could someone help me out. Thanks
我的应用程序总是崩溃。有人可以帮我吗。谢谢
采纳答案by Boris Mocialov
Color.parseColor("#rrggbb")
Color.parseColor("#rrggbb")
instead of #rrggbb
you should be using hex values 0 to F for rr, gg and bb:
而不是#rrggbb
你应该为 rr、gg 和 bb 使用十六进制值 0 到 F:
e.g. Color.parseColor("#000000")
or Color.parseColor("#FFFFFF")
例如Color.parseColor("#000000")
或Color.parseColor("#FFFFFF")
From documentation:
从文档:
public static int parseColor (String colorString):
Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'
公共静态 int parseColor (String colorString):
解析颜色字符串,返回对应的color-int。如果无法解析字符串,则抛出 IllegalArgumentException 异常。支持的格式有:#RRGGBB #AARRGGBB 'red'、'blue'、'green'、'black'、'white'、'gray'、'cyan'、'magenta'、'yellow'、'lightgray'、'darkgray ', '灰色', '浅灰色', '深灰色', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'
So I believe that if you are using #rrggbb
you are getting IllegalArgumentExceptionin your logcat
所以我相信,如果你正在使用#rrggbb
你的 logcat,你会得到IllegalArgumentException
Alternative:
选择:
Color mColor = new Color();
mColor.red(redvalue);
mColor.green(greenvalue);
mColor.blue(bluevalue);
li.setBackgroundColor(mColor);
回答by Guy
Try this:
尝试这个:
li.setBackgroundColor(android.R.color.red); //or which ever color do you want
EDIT: Posting logcat file would also help.
编辑:发布 logcat 文件也会有所帮助。
回答by sherin
This question is a old one but it can help for others too.
这个问题是一个古老的问题,但对其他人也有帮助。
Try this :
尝试这个 :
li.setBackgroundColor(getResources().getColor(R.color.blue));
or
li.setBackgroundColor(getResources().getColor(android.R.color.red));
or
li.setBackgroundColor(Color.rgb(226, 11, 11));
or
li.setBackgroundColor(Color.RED)
回答by Handel 38
By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:
顺便说一下,在新版本的 AS 上快速选择颜色的一个很好的技巧是简单地键入 #fff,然后使用代码一侧的颜色选择器来选择您想要的颜色。比记住所有颜色十六进制更快更容易。例如:
android:background="#fff"