Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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.

like image 937
Linus Avatar asked Sep 14 '14 20:09

Linus


People also ask

What is a hex background color?

Background-color values can be expressed in hexadecimal values such as #FFFFFF, #000000, and #FF0000. Background-color values can be expressed using rgb such as rgb(255,255,255), rgb(0,0,0), and rgb(255,0,0). Background-color values can be expressed as named colors such as white, black, and red.

What color is 0xff0000?

Black = 0x000000. A "perfect" Blue = 0x0000ff. A "prefect" Red = 0xff0000.


2 Answers

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.

like image 82
Tom Avatar answered Sep 30 '22 20:09

Tom


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

like image 35
FreshD Avatar answered Sep 30 '22 19:09

FreshD