'.setBackgroundColor with Hex Color Codes AndroidStudio
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)'
and : Cannot resolve method'pasrsehexString(java.lang.String)'
Pleas can somebodey help me and by the way i'm using Android Studio.
Solution 1:[1]
There are two main classes for color handling in 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:
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.
int red = Color.parseColor("#FF0000");
So you should check which kind of Color class 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.
Solution 2:[2]
Define your color in the resource File 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
Solution 3:[3]
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 int literals for it. For example:
targetView.setBackgroundColor(0xffffffff);
where the color is in ARGB.
Solution 4:[4]
If you use Kotlin these ways can help you, you don't need import any extra Libs.
1- Direct by 0X like this, (So-So)
dialogMiddleButton.setBackgroundColor(0XF00092)
2- Use Color.parseColor like this:(The best one)
dialogCardView.setCardBackgroundColor(Color.parseColor("#F06292"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tom |
| Solution 2 | |
| Solution 3 | laalto |
| Solution 4 | Mori |
