Applying coloring

We defined the color palette for our application. We applied each color by accessing its resource. Sometimes we do not have a particular color resource available. It can happen that we obtained the color dynamically through the backend (in a response to some API call) or we want the color to be defined from the code because of some other reasons.

Android is very powerful when you need to deal with colors from your code. We will cover some examples and show you what you can do.

To get color from an existing resource you can do the following:

    val color = ContextCompat.getColor(contex, R.color.plum) 

Before we used to do this:

     val color = resources.getColor(R.color.plum) 

But it is deprecated from Android version 6.

When you obtained a color you can apply it on some view:

    pick_date.setTextColor(color) 

Another way to obtain a color is by accessing Color class static methods. Let's start with parsing some color string:

    val color = Color.parseColor("#ff0000")  

We must note that there is already a certain number of predefined colors available:

     val color = Color.RED 

So we don't need to parse #ff0000. There are some other colors as well:

    public static final int BLACK 
    public static final int BLUE 
    public static final int CYAN 
    public static final int DKGRAY 
    public static final int GRAY 
    public static final int GREEN 
    public static final int LTGRAY 
    public static final int MAGENTA 
    public static final int RED 
    public static final int TRANSPARENT 
    public static final int WHITE 
public static final int YELLOW

Sometimes you will have only parameters about red, green, or blue and based on that to create a color:

     Color red = Color.valueOf(1.0f, 0.0f, 0.0f); 

We must note that this method is available from API version 26!

If RGB is not your desired color space then you can pass it as a parameter:

    val colorSpace = ColorSpace.get(ColorSpace.Named.NTSC_1953) 
    val color = Color.valueOf(1f, 1f, 1f, 1f, colorSpace) 

As you can see there are a lot of possibilities when you deal with the color. If standard color resources are not enough for you to manage your colors you can do it in an advanced way. We encourage you to play with it and try on some user interfaces.

For example, if you are using the AppCompat library once you get Color instance you can use it like in the following example:

    counter.setTextColor( 
      ContextCompat.getColor(context, R.color.vermilion) 
    ) 

Consider the following screenshot: