.setBackgroundColor with AndroidStudio hex color codes

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


it works but



and it didn't work



Error: Cannot resolve method_parseColor (java.lang.String) '

and: Cannot resolve method_pasrsehexString (java.lang.String) '

Wishlist may help me and by the way I am using Android Studio.


source to share

3 answers

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

This is the first of the "simple" Java and can be found in java.awt.Color

. This class supports converting String to color using the decode method . Example:

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


The second class is for Android and can be found in android.graphics.Color

. Conversion can be done using the parseColor method .

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


So you have to check what type of Color

class you have imported into your project. I recommend using the Android version of color for your case. If you have done this, then the instruction targetView.setBackgroundColor(Color.parseColor("#FFFFFF"));

should work.



Define your color in resource color.xml file

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


and set Backgroundcolor



This might be helpful: Color.xml



No need to parse line colors in your code.

If you want to hard-code the color values ​​in your code (rather than using color resources as in FreshD's answer), you can use int

literals for it. For example:



where the color is in ARGB.



All Articles