Colors in java android

Класс android.graphics.Color

В графике важную роль играет цвет, который представлен классом Color. Класс Color содержит несколько констант и методов для конвертации и извлечения цветового компонента.

Цвета можно описывать четырьмя числами в формате ARGB, по одному для каждого канала(Alpha, Red, Green, Blue). Каждый из каналов является восьмибитным целым числом и может принимать значения от 0 до 256. Обычно цвет упаковывают в 32-битное целое число. Стоит отметить, что использовать целые числа для цветов эффективнее, чем экземпляры класса Color.

Если все значения RGB-каналов установить равными 0, то получим чёрный цвет, если присвоить значения 255, то получим белый цвет.

Иногда значения указываются не в десятичной форме, а в шестнадцатеричной от 00 до FF, вместо 0 и 255. В этом случае обычно пишут не ARGB, а AARRGGBB. Например, красный цвет в данном формате будет равен FFFF0000 (AA = FF, RR = FF, GG = 00, BB = 00).

Для создания цвета можно использовать статические константы класса Color, например:

Таких констант немного, только для основных цветов.

Получить красную, зелёную и синюю составляющую цвета можно через методы red(), green, blue(). Получить нужный цвет из набора компонентов можно через методы rgb() и argb(), которые вернут вам int-значение цвета.

Метод parseColor() позволяет получить int-значение из шестнадцатеричной формы.

Лучше задавать цвет в ресурсах для большей гибкости. Всегда можно будет поменять в случае необходимости без вмешательства в код программы:

В коде можно обратиться к цвету следующим образом:

Создадим простейший пример для просмотра цветов.

Код для активности:

Запустив проект, вы можете выбирать из выпадающего списка нужный цвет, чтобы закрасить им фон LinearLayout.

Кроме стандартной цветовой модели RGB используется также Цветовая модель HSV

Источник

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.

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:

Источник

Android styling: common theme attributes

In the previous article in this series on Android styling, we looked at the difference between themes and styles and how themes allow you to write more flexible styles and layouts which isolate changes:

Android Styling: Themes vs Styles

The Android styling system offers a powerful way to specify your app’s visual design, but it can be easy to misuse…

Specifically we recommended using theme attributes to provide a point of indirection to resources, so that you can vary them (e.g. in dark theme). That is, if you find yourself writing a direct resource reference (or worse yet, a hardcoded value 😱) in a layout or style, consider if you should use a theme attribute instead.

But what theme attributes are available to use? This post highlights the common ones that you should know about; those that come from Material, AppCompat or the platform. This is not a complete list (for that I’d recommend browsing the attrs files linked below where they are defined) but these are the attributes that I use all the time.

Colors

Many of these colors come from the Material color system, which defines semantic names for colors that you can use throughout your app (implemented as theme attrs).

  • ?attr/colorPrimary The primary branding color for the app.
  • ?attr/colorSecondary The secondary branding color for the app, usually a bright complement to the primary branding color.
  • ?attr/colorOn[Primary, Secondary, Surface etc] A color which contrasts against the named color.
  • ?attr/color[Primary, Secondary]Variant An alternate shade of the given color.
  • ?attr/colorSurface A color for surfaces of components, such as cards, sheets, and menus.
  • ?android:attr/colorBackground The background for the screen.
  • ?attr/colorPrimarySurface switches between colorPrimary in the Light themes, colorSurface in the Dark theme.
  • ?attr/colorError A color for displaying errors.

Other handy colors:

  • ?attr/colorControlNormal The color applied to icons/controls in their normal state.
  • ?attr/colorControlActivated The color applied to icons/controls in their activated state (e.g. checked).
  • ?attr/colorControlHighlight The color applied to control highlights (e.g. ripples, list selectors).
  • ?android:attr/textColorPrimary The most prominent text color.
  • ?android:attr/textColorSecondary Secondary text color.
Читайте также:  Hollywood story взлом андроид

Dimens

  • ?attr/listPreferredItemHeight Standard (min) height for list items.
  • ?attr/actionBarSize The height of a toolbar.

Drawables

  • ?attr/selectableItemBackground A ripple/highlight for interactive items (also handy for foregrounds!!)
  • ?attr/selectableItemBackgroundBorderless An unbounded ripple.
  • ?attr/dividerVertical A drawable that may be used as a vertical divider between visual elements.
  • ?attr/dividerHorizontal A drawable that may be used as a horizontal divider between visual elements.

TextAppearances

Material defines a type scale — a discrete set of text styles that you should use throughout your app, each of which is provided as a theme attribute which can be set as a textAppearance . Check out the Material type scale generator to help generate a scale for different fonts.

  • ?attr/textAppearanceHeadline1 defaults to light 96sp text.
  • ?attr/textAppearanceHeadline2 defaults to light 60sp text.
  • ?attr/textAppearanceHeadline3 defaults to regular 48sp text.
  • ?attr/textAppearanceHeadline4 defaults to regular 34sp text.
  • ?attr/textAppearanceHeadline5 defaults to regular 24sp text.
  • ?attr/textAppearanceHeadline6 defaults to medium 20sp text.
  • ?attr/textAppearanceSubtitle1 defaults to regular 16sp text.
  • ?attr/textAppearanceSubtitle2 defaults to medium 14sp text.
  • ?attr/textAppearanceBody1 defaults to regular 16sp text.
  • ?attr/textAppearanceBody2 defaults to regular 14sp text.
  • ?attr/textAppearanceCaption defaults to regular 12sp text.
  • ?attr/textAppearanceButton defaults to medium all caps 14sp text.
  • ?attr/textAppearanceOverline defaults to regular all caps 10sp text.

Shape

Material employs a shape system which is implemented as theme attrs for small, medium and large components. Note that if you’re setting a shape appearance on a custom component, you likely want to use a MaterialShapeDrawable as it’s background which understands and implements the shaping.

  • ?attr/shapeAppearanceSmallComponent used for Buttons, Chips, Text Fields etc. Defaults to rounded 4dp corners.
  • ?attr/shapeAppearanceMediumComponent used for Cards, Dialogs, Date Pickers etc. Defaults to rounded 4dp corners.
  • ?attr/shapeAppearanceLargeComponent used for Bottom Sheets etc. Defaults to rounded 0dp corners (i.e. square!)

Button Styles

This might seem super specific, but Material defines three types of buttons: Contained, Text and Outlined. MDC offers theme attrs that you can use to set the style of a MaterialButton :

  • ?attr/materialButtonStyle defaults to contained (or just omit the style).
  • ?attr/borderlessButtonStyle for a text style button.
  • ?attr/materialButtonOutlinedStyle for outlined style.

Floats

  • ?android:attr/disabledAlpha Default disabled alpha for widgets.
  • ?android:attr/primaryContentAlpha The alpha applied to the foreground elements.
  • ?android:attr/secondaryContentAlpha The alpha applied to secondary elements.

App vs Android namespace

You might have noticed that some attributes are referenced by
? android:attr/foo and others just by ?attr/bar . This is because some are defined by the Android platform, and as such you need the android part to reference them by their namespace (just like with view attributes in layouts: android:id ). Those without come from static libraries (i.e. AppCompat or MDC) which are compiled into your application, so don’t need the namespace (similar to how you might use app:baz in a layout). Some elements are defined both in the platform and in a library e.g. colorPrimary . In these cases, prefer the non-platform version, as this can be used on all API levels i.e. they’re duplicated in a library precisely to backport them. In these cases, I’ve listed the non-platform versions above.

prefer non-platform attributes which can be used on all API levels

More Resources

For a complete list of the theme attributes available to use, go to the source of truth:

Material Design Components:

Do It Yourself

Sometimes there isn’t a theme attribute which abstracts something you’d like to vary by theme. No worries… create your own! Here’s an example from the Google I/O app which shows a list of conference sessions in two screens.

They’re largely similar but the left screen must leave space for the sticky time headers while the right screen does not. We implemented this by abstracting where to align items behind a theme attribute so that we can vary them by theme and use the same layout across two different screens:

1. Define the theme attribute in attrs.xml

2. Provide different values in different themes:

3. Use the theme attr in the single layout used on both screens (each using one of the above themes):

Question (mark) everything

Knowing what theme attributes are available, equips you to use them when writing your layouts, styles or drawables. Using theme attributes makes it much easier to support theming (like dark theme) and to write more flexible, maintainable code. For a deep dive on this, join us in our next post in this series:

Источник

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