Color numbers in android

Tek Eye

How does color work in Android? An Android color is a 32-bit integer value consisting of four eight bit parts (4×8=32). The four parts are tagged ARGB. This is the amount of Red, Green and Blue in the color, plus how opaque (see through) it is, called the Alpha value, the lower the alpha value the more transparent the color appears. (Note that in British English color is spelt colour.) This article shows how to set a color in Android and provides some demo code to try out.

(This Android color tutorial assumes that Android Studio is installed, a basic app can be created and run, and the code in this article can be correctly copied into Android Studio. The example code can be changed to meet your own requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter.)

Changing Colors in Android and Naming Them for Convenience

The alpha value is the highest (first) byte in the 32-bit value, followed by the red, then green and finally the blue byte. Hence it is referred to as an ARGB value with each letter representing the type and order of the byte. This format allows for easy representation as a hexadecimal number in Java. Add this code to the basic starting app at the bottom of the onCreate in the MainActivity.java (the TextView displaying Hello World! is given the ID of textView):

The three byes representing the color values provide over 16 million color possibilities in Android (256 x 256 x 256 = 16,777,216). A color depth better than the human eye (stated in the Wikipedia article). Plus all these colors can range from transparent (completely see through when alpha is 0), to opaque (completely solid when alpha is 255).

Named Color Resources in Android

To help with handling colors in Android they can be made into a resource for easy reuse. Either open an existing resource file or create a new one. In the Android Studio project there should be a colors.xml file in the res/values folder. In colors.xml add a definition for the required color, Lime is defined here as an example:

(Note: To add a new resource first select the app in the Project explorer file. Then use the File or context menu, usually right-click, then the New option and select Android resource file. A color resource does not need to be stored in colors.xml, other file names can be used.)

Use getColor() to read the color value from the resource:

If the color is solid (full alpha value) then the color resource can leave the alpha value out. Though for clarity and future maintenance it is wise to be explicit and always define all four parts of an Android color:

The use of a named color in a resource file is handy when dealing with common colors (such as the standard HTML named web colors, i.e. CSS colors, or X Window System and SVG color names). A resource file can be created to define the common colors for an app. Here is a resource file to use the HTML/CSS color names in Android code:

Читайте также:  Звук нажатия клавиш клавиатуры андроид

Then just use them as required:

Referencing Colors in Android XML Layouts

To reference an Android color resource in an XML layout simple use @color/name_of_color, the same way other resources are referenced, such as strings:

Accessing Android System Color Resources

Are there predefined colors in Android? Yes, there are existing color resources, but not many. Also Google does not recommend using certain system resources as they are not guaranteed to stay the same in future releases, or even be there. You can browse the Android color resources in an app project. Select Packages at the top of the Project explorer in Studio. Expand the Libraries and android, in the R.class view the items in class color. There are resources such as R.color.black and R.color.holo_purple. The full list is also available in the R.color developer documentation. To access these resources you need the package qualifier, as in @android:color/black. In code add android before the R:

Note that the Android color resources starting holo are not available on versions of Android prior to API level 14 (Ice Cream Sandwich).

The Android Color Class

There is a helper class in Android that has functions to ease the generation of color values from individual alpha, red, green and blue components, from strings and from Hue, Saturation and Value (HSV), and back again. The Color class defines a limited range of static colors, e.g. Color.YELLOW, see the Android developer documentation for full information on the Color class:

Android Color class static constants: BLACK, BLUE, CYAN, DKGRAY, GRAY, GREEN, LTGRAY, MAGENTA, RED, TRANSPARENT, WHITE, YELLOW

Color class methods: HSVToColor, RGBToHSV, alpha, argb, blue, colorToHSV, green, parseColor, red, rgb

Android Oreo Introduced ColorSpace

Android Oreo (API 26) introduce advanced color models that go beyond the previous RGB model, e.g. CMYK (the cyan, magenta, and yellow key format). For most apps the RGB colors are fine. However, for specialised applications the new models may be required. See the article Enhancing Graphics with Wide Color Content and the ColorSpace documentation on Android Developers.

For wide color support the Color class was expanded to provide 64 bit color values. Existing methods now come with support for long, and the new methods are: colorspace, convert, getColorSpace, getComponent, getComponentCount, getComponents, getMaxValue, getMinValue, getModel, isInColorSpace, isSrgb, isWideGamut, luminance, pack, toArgb

Changing Text Color in Android

Use the textColor attribute to modify the color of text when it is defined in an XML layout:

Android Color Codes Example Project

To see all the above Android color hexadecimal codes and named colors in action use the color test demo project. Here are examples of the above in action:

Download color-test.zip, extract it to a folder on your development PC and import it into Android Studio. This sample Android colors project is also available from the Tek Eye Android Example Projects page, where further details on importing a sample project into Studio is provided.

Adding a Color Picker to an App

If you need to add the ability to configure a color for a setting in an app it is easily done. The Android SeekBar can be used for a quick and easy color picker, drop four SeekBars onto a layout, one for each component of a color (only three are needed if you do not want to change the transparency). Use the methods from the Color class to combine the SeekBar outputs into the color value. Here’s one in action:

An article on building the above color picker is available in the Android Color Picker Tutorial. That tutorial also covers the color picker available in the original Android API Demos app. The API Demos project was in the pre-Androud Studio versions of the Android Software Development Kit (SDK). In API Demos the color picker is in ColorPickerDialog.java.

There are also plenty of other Android color pickers available, with full source, on GitHub, simply search for Android color picker.

Читайте также:  Firefox browser apk android tv

And Finally.

What is the color of the Android Robot? Android green is 0xA4C639.

Summary

Storing ARGB color values in an Android resource files, e.g. #FFFF0000 , makes it easy to remember the color values for Views in Layouts. The names are easier to remember than hex strings. There is a Color helper class available to help with color conversion and value extraction. Several free color picker Views are available to add color selection functionality to apps.

See Also

  • Download the code for this example, available in color-test.zip
  • An Android Color Picker Tutorial with example source code and project.
  • See Color State List Resource for information on changing colors in Views on different states.
  • See the Android Studio example projects to learn Android app programming.
  • For a full list of all the articles in Tek Eye see the full site Index.

Acknowledgements

Author: Daniel S. Fowler Published: 2013-04-15 Updated: 2017-11-26

Do you have a question or comment about this article?

(Alternatively, use the email address at the bottom of the web page.)

↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.

Free Android Projects and Samples:

Источник

How can I get color-int from color resource?

Is there any way to get a color-int from a color resource?

I am trying to get the individual red, blue and green components of a color defined in the resource (R.color.myColor) so that I can set the values of three seekbars to a specific level.

13 Answers 13

Check here on how to define custom colors:

EDIT(1): Since getColor(int id) is deprecated now, this must be used :

(added in support library 23)

EDIT(2):

Below code can be used for both pre and post Marshmallow (API 23)

Based on the new Android Support Library (and this update), now you should call:

This method was deprecated in API level 23. Use getColor(int, Theme) instead

It is the same solution for getResources().getColorStateList(id) :

You have to change it like this:

EDIT 2019

Regarding ThemeOverlay use the context of the closest view:

So this way you get the right color based on your ThemeOverlay.

Specially needed when in same activity you use different themes, like dark/light theme. If you would like to understand more about Themes and Styles this talk is suggested: Developing Themes with Style

Define your color

Get the color int and set it

See also

Best Approach

As @sat answer, good approach for getting color is

or use below way when you don’t have access to getResources() method.

What i do is

It is most simple to use anywhere in your app! Even in Util class or any class where you don’t have Context or getResource()

Problem (When you don’t have Context)

When you don’t have Context access, like a method in your Util class.

Assume below method without Context.

Now you will pass Context as a parameter in this method and use getResources().

So here is a Bonus unique solution by which you can access resources from anywhere like Util class . Add Resources to your Application class or Create one if does not exist.

Источник

How to get a Color from hexadecimal Color String

I’d like to use a color from an hexa string such as «#FFFF0000» to (say) change the background color of a Layout. Color.HSVToColor looks like a winner but it takes a float[] as a parameter.

Am I any close to the solution at all?

15 Answers 15

Try Color class method:

Supported formats are: #RRGGBB #AARRGGBB ‘red’, ‘blue’, ‘green’, ‘black’, ‘white’, ‘gray’, ‘cyan’, ‘magenta’, ‘yellow’, ‘lightgray’, ‘darkgray’

This question comes up for a number of searches related to hex color so I will add a summary here.

Color from int

Hex colors take the form RRGGBB or AARRGGBB (alpha, red, green, blue). In my experience, when using an int directly, you need to use the full AARRGGBB form. If you only have the RRGGBB form then just prefix it with FF to make the alpha (transparency) fully opaque. Here is how you would set it in code. Using 0x at the beginning means it is hexadecimal and not base 10.

Читайте также:  Живые обои животные для андроида

Color from String

As others have noted, you can use Color.parseColor like so

Note that the String must start with a # . Both RRGGBB and AARRGGBB formats are supported.

Color from XML

You should actually be getting your colors from XML whenever possible. This is the recommended option because it makes it much easier to make color changes to your app. If you set a lot of hex colors throughout your code then it is a big pain to try to change them later.

Android material design has color palates with the hex values already configured.

These theme colors are used throughout your app and look like this:

If you need additional colors, a good practice to follow is to define your color in two steps in xml. First name the the hex value color and then name a component of your app that should get a certain color. This makes it easy to adjust the colors later. Again, this is in colors.xml.

Then when you want to set the color in code, do the following:

Android Predefined colors

The Color class comes with a number of predefined color constants. You can use it like this.

Источник

Change the text color of NumberPicker

I’ve looked at most all of the threads on this and none provided an answer that works. Styling the NumberPicker does not work (as per this thread: NumberPicker textColour)

Setting the style attribute on the numberPicker to a style that has a color item does not have any effect either. Nor does setting the textColor attribute on the numberPicker XML do anything.

Closest I’ve got to this is using the numberPicker to cast its getChildAt() to an EditText and then do setColor() on that EditText, but that only changes the color of the child once upon initialization and then every time it is selected from thereon; not what I am looking for either.

Any help? Thanks

10 Answers 10

The solution I tried and worked for me is:

In styles.xml add:

Then use it like this inside your layout:

This code should solve your problem. The problem you are experiencing is because during the construction of NumberPicker it captures the EditText textColor and assigns to to a paint so it can draw the numbers above and below the edit text with the same color.

Not sure why you would need to dive into Java Reflection API for this. Its a simple styling matter. The attribute that you need to override is: textColorPrimary .

If you’re using the TimePicker inside a Dialog , override android:textColorPrimary in the dialog’s theme.

Additional info:

Here’s an insightful comment by Yoann Hercouet:

This solution does not change only the color on the NumberPicker, it is a global change that will impact A LOT of components

This is correct, but it overlooks the possibilities I am hinting at. Moreover, global implies app-wide impact. That can be limited to activity-scope by applying this theme only to activities containing the NumberPicker . But, I agree, this may still be too corrosive.

The idea here is to somehow inject textColorPrimary=INTENDED_COLOR into the theme that will be seen by NumberPicker . There are multiple ways to achieve this. Here’s one way:

Define a bare-bone style in res/values/styles.xml :

Now, create a custom NumberPicker :

Finally, use ThemedNumberPicker in your layout(s):

We have successfully contained the impact that textColorPrimary=INTENDED_COLOR has on our app.

This is of course just one option. For example, if you were inflating a layout containing a NumberPicker , you could use:

Источник

Оцените статью