Coloronprimary android studio что это

от admin

Material Theming with MDC: Color

Material Theming is a way to customize Material Components to align with your brand. A Material theme includes color, typography and shape parameters which you can adjust to get near-infinite variations of the components — all while maintaining their core anatomy and usability.

On Android, Material Theming can be implemented using the Material Components (MDC) library, from version 1.1.0 onwards. If you’re looking to migrate from the Design Support Library or MDC 1.0.0 , take a look at our migration guide.

Migrating to Material Components for Android

From Design Support Library �� MDC 1.0.0 �� MDC 1.1.0 and beyond

This article will be focusing on color theming.

Color attributes

Material Design provides 12 color “slots” that make up the overall palette of your app. Each of these have a design term (eg. “Primary”) along with a corresponding color attribute that can be overridden in your app theme (eg. colorPrimary ). There are default “baseline” values for both your light theme and dark theme.

Material Components use these color attributes to tint elements of the widgets.

They are applied with eg.

in layouts and widget styles.

You might recognise some of these color attributes like colorPrimary . That’s because a few of them are inherited from AppCompat and the platform, while the rest have been newly introduced by MDC. The table below illustrates the origin of each attribute.

Picking colors

Figuring out which color values to use for each slot may be the responsibility of a designer, or derived from your product’s brand. However, it’s still useful to know about the role of each color, the relationship between them, and how to meet accessibility requirements:

  • colorPrimary and colorSecondary represent the colors of your brand
  • colorPrimaryVariant and colorSecondaryVariant are lighter or darker shades of your brand colors
  • colorSurface is used for “sheets” of material (like cards and bottom sheets)
  • android:colorBackground is the window background color of your app
  • colorError is, as the name suggests, for errors and warnings
  • The various “On” colors ( colorOnPrimary , colorOnSecondary , colorOnSurface , etc.) are used to tint foreground content (such as text and icons) displayed on top of the other colors. They need to meet accessibility requirements and have sufficient contrast against the colors they’re displayed on.

Color tools

Material Design provides useful tools for previewing colors and determining suitable variants and “On” colors:

    : Get light/dark variants of your primary and secondary colors as well as the appropriate “On” color. Preview how these will look in sample screens. : Generate a full tonal palette (shade 50–900) for a color. Get suggestions of complementary, analogous, and triadic colors.

Things to consider

  • You almost always want to override colorPrimary , colorSecondary and their variants, unless your brand happens to use the exact same purple/teal hex values as the baseline Material Theme.
  • You don’t have to override all colors. Some, such as colorSurface , use neutral colors so relying on the default values is perfectly fine.
  • If your brand does not define any kind of secondary or accent color, it’s ok to use a single color for both colorPrimary and colorSecondary . The same can be said of variants (eg. colorPrimary and colorPrimaryVariant could be the same).
  • Despite being separate attributes, there’s an inherent link between a color, its variant (if one exists) and its “On” color (eg. colorPrimary , colorPrimaryVariant and colorOnPrimary ). Overriding one means checking the others to see if they make sense and meet accessibility requirements.

Additional color slots

Your design system may call for additional color slots outside of the 12 that Material Theming specifies. Thankfully this is relatively easy to do on Android by declaring a color attr:

Color resources

Color values are defined as <color> resources. For custom colors we recommend two approaches to help separate concerns, and create a single source of truth for color theming values in your app:

  • Store all <color> s in a single res/values/colors.xml file
  • Use literal names for <color> s that describe the value as opposed to assigning semantic meaning:
  • Doing so encourages the use of ?attr/ references when using colors, which is a recommended approach for supporting dark themes
  • Use names like green_500 or brand_name_yellow
  • Avoid semantic names like color_primary

Overriding colors in an app theme

Let’s take a look at how you can add your chosen color palette to your app theme by overriding relevant attributes.

First, we recommend setting up your theme(s) to gracefully handle light and dark color palettes while reducing repetition with base themes. For more on this topic, take a look at Chris Banes’ article on dark theme as well as the “Developing Themes with Style” talk given by him and Nick Butcher.

Dark Theme with MDC

Using Material Design Components to implement a dark theme

Once set up, override the color attributes you wish to change in your light and dark themes:

Material Components will respond to theme-level color overrides:

Color reusability and best practice

There are many circumstances which involve using colors in layouts, drawables, styles, and elsewhere. We’re going to go through some approaches to make your code as reusable as possible, regardless of the color values specified in your app theme.

Prefer attrs

The most important thing we suggest is to use ?attr/ color references. This is the recommended approach to creating reusable layouts and default styles that support multiple themes like light/dark.

Take a look at Nick Butcher’s “Android Styling: Prefer Theme Attributes” article for further explanations and some exceptions to the rule.

Android styling: prefer theme attributes

Theme attribute all the things

Colors with alpha

There are times when you may want to use one of the colors from your MDC theme with an alpha value eg. colorPrimary at 60%. Examples of this include touch ripples and checked state overlays.

Android <color> resources do allow for an alpha channel:

However, with this approach we need to maintain separate color resources per alpha value. It also means we can’t use these as ?attr/ s and goes against our single source of truth approach mentioned above.

Rather, we suggest taking advantage of ColorStateList s stored in your res/color directory. A CSL can have a single item which includes a color reference and an alpha value, which is perfect for our use case:

Using these might cause you to raise an eyebrow — they’re referenced with the @color/primary_60 notation — but this is fine considering we’re dealing with a CSL that itself uses ?attr/ to reference the underlying theme color.

Colors per state and theme overlays

ColorStateList s are more commonly used to switch between colors (and alpha values) depending on the state of the view. MDC widgets use this generously for disabled states, hovered vs. pressed states and so on. Here’s an example of a button’s background tint from the MDC source code:

Keeping with the button example, suppose you want to change the main background tint from primary to secondary:

You could copy the above source file into your codebase and change colorPrimary to colorSecondary , but this is tedious and becomes problematic if the source code happens to change.

A better way to do this is to use theme overlays. Nick Butcher goes into detail about this in his “Android Styling: Themes Overlay” post. Essentially we can replace the value of a specific theme attribute ( colorPrimary in our case) for a particular View or ViewGroup and any descendants (in our case a button).

Android Styling: themes overlay

In previous articles in this series on Android styling, we’ve looked at the difference between styles and themes…

A basic theme overlay can be seen below. Note the empty parent, which ensures we only override the attrs we wish to change:

When applying theme overlays in XML, there are two options to consider:

  • android:theme : Works with all widgets, doesn’t work in default styles
  • app:materialThemeOverlay : Only works with MDC widgets (or in custom views using MaterialThemeOverlay#wrap), does work in default styles

API compatibility

Platform support for ?attr/ s in CSLs and elsewhere was only added in API 23. If your minSdk is below this, don’t worry: compatibility classes do exist! In fact, both MDC and AppCompat widgets make use of these under-the-hood so no additional work is required when using them.

For scenarios where you need to use CSLs programmatically, use AppCompatResources :

Color in MDC widgets

Earlier we said that MDC widgets respond to overrides of theme level color attributes. But how would you know, for example, that a button uses colorPrimary as its background tint and colorOnPrimary for its icon and text label? Let’s take a look at a few options.

Build a Material Theme

Build a Material Theme is an interactive Android project that lets you create your own Material theme by customizing values for color, typography, and shape. It also includes a catalog of all theming parameters and components. Determining which widgets respond to changes in theme color attributes can be done by:

  • Cloning the project and running the app in Android Studio
  • Adjusting values in res/values/color.xml as well as res/values/themes.xml and res/values-night/themes.xml
  • Observing visual changes by re-running the app

MDC developer docs

The MDC developer docs have recently been refreshed. As part of this we’ve included attribute tables which include design terminology and default values used in the library. For example, check out the “Anatomy and key properties” sections of the updated buttons doc.

Source code

Inspecting the MDC source code is arguably the most reliable approach. MDC uses default styles to achieve Material Theming so it’s a good idea to look at these as well as any styleable attrs and the java file(s). For example, check out the styles, attrs and java file for MaterialButton .

Color in custom views

Your app may include custom widgets you’ve built or gotten from an existing library. Making these views responsive to Material Theming is useful when using them alongside standard MDC widgets. Let’s take a look at what to keep in mind when supporting color theming for custom widgets.

Use MDC attrs in <declare-styleable> s and default styles

Allowing your custom views to be styled involves using a <declare-styleable> . Reusing attr names from MDC can be useful for consistency. Default styles that use <declare-styleable> s can also reference MDC theme color attrs for their values:

MaterialColors utility class

Resolving theme color attrs programmatically can be done with a handy new MDC class — MaterialColors — which may also be useful for custom views:

OK Google, what’s next?

We’ve been through the process of implementing color theming in your Android app using MDC. Be sure to check out our other posts in this series on why we recommend using MDC, type theming, shape theming, dark theme, and Material’s motion system.

Темы и стили

Чтобы наше приложение было стильным, можно воспользоваться специальной темой. Тема — это коллекция стилей, которые обеспечивают профессиональный вид приложению, чтобы оно было похоже на родные приложения Android. Сама система Android уже имеет несколько предустановленных тем, которыми можно воспользоваться в своих целях. Вам достаточно только указать имя темы в манифесте.

В предыдущем примере мы учились переключаться на другой экран, чтобы увидеть новое окно О программе. Сделаем это окно диалоговым, чтобы оно не занимало весь экран.

Откройте снова файл манифеста AndroidManifest.xml из прошлого урока и измените строчку для активности AboutActivity, указав тему.

Запустив программу, вы увидите, что внешний вид окна «О программе» стал уже другим. Сравните.

Dialog theme

Обратите внимание, что теперь появляется не окно во весь экран, а диалоговое окно в центре экрана. При этом остальная часть экрана затемняется.

Похожие темы: android:theme=»@style/Theme.AppCompat.Light.Dialog», android:theme=»@style/Theme.AppCompat.Light.Dialog.MinWidth», android:theme=»@style/Theme.AppCompat.Dialog.MinWidth».

Тему можно применить не только к отдельной активности, но и ко всем активностям приложения, если прописать в теге application.

Кстати, вы можете разработать свою тему на основе существующих и сохранить ее в файле res/values/styles.xml.

Стили и темы — это такие же ресурсы, как и строки, изображения и т. д. Android обеспечивает некоторые заданные по умолчанию стили и темы, которые вы можете использовать в приложениях. При необходимости вы можете определить свой собственный стиль и тему для создаваемого приложения.

Стили

Стиль — это один или несколько сгруппированных атрибутов форматирования, которые отвечают за внешний вид и поведение элементов или окна. Стиль может задавать такие свойства, как ширину, отступы, цвет текста, размер шрифта, цвет фона и так далее. Сами стили хранятся в XML-файлах, отдельно от файлов разметки.

Подобное разделение напоминает использование каскадных стилей CSS для веб-документов, которые также отвечают за стили HTML-элементов и хранятся в отдельных файлах.

Предположим, у нас есть следующий код разметки для TextView:

Мы можем вынести все свойства в файл стилей следующим образом:

res/values/styles.xml

Тогда в файле разметки теперь будет так:

Как видите, мы удалили все свойства для текста из файла разметки и разместили их в файле стилей в ресурсе под именем MyTextStyle, который содержит теперь все необходимые свойства.

Создать файл со стилями несложно. Создаем новый XML-файл в папке res/values/ вашего проекта. Имя файла не имеет значения, главное, чтобы расширение было XML, а сам файл находился в указанной папке. В проекте, создаваемом студией, уже есть готовый файл res/values/styles.xml, в который вы можете добавить новые стили. А также вы можете создать свой отдельный файл стилей.

Корневым узлом файла должен быть элемент <resources>. Для каждого элемента, которому требуется стиль, нужно добавить элемент <style> с уникальным именем. Далее создаются элементы <item> для каждого свойства и присваиваются им имена, которые отвечают за выбранное свойство. Значением элемента <item> должно выступать ключевое слово, цвет в шестнадцатеричном значении, ссылка на другой тип ресурсов или другое значение в зависимости от свойства стиля. Ниже представлен образец такого стиля:

Во время компиляции все свойства из файла стилей будут извлечены и применены к элементам.

Атрибут parent для элемента style является необязательным и позволяет задавать идентификатор ресурса другого стиля, из которого нужно наследовать свойства. При этом вы можете переопределить свойства в случае необходимости.

Быстрое создание стилей через Android Studio

Если вы решили вынести некоторые свойства компонентов в стили, то необязательно это делать вручную. В студии есть удобный инструмент для быстрого создания ресурсов стилей.

В текстовом режиме щёлкните правой кнопкой мыши на нужном компоненте и в контекстном меню выбирайте пункт Refactor | Extract | Style. Далее укажите имя стиля и выберите требуемые параметры для экспорта. Студия самостоятельно создаст стиль в файле styles.xml и автоматически применит созданный ресурс в layout-файле.

Наследование стилей

Наследование — мощный и полезный механизм, позволяющий не изобретать велосипед, а использовать готовые проверенные наработки. С помощью атрибута parent в элементе style вы можете наследовать нужные свойства из существующих стилей, а также переопределить некоторые свойства или добавить свои дополнительные свойства. Предположим, мы решили наследоваться от существующего системного стиля Android для текстовых сообщений и слегка модифицировать его.

Если вы собираетесь наследоваться от собственных стилей, то использовать атрибут parent не нужно. Просто используйте префикс имени наследуемого стиля перед создаваемым новым стилем, разделяя имена стилей точкой. Например, для создания нового стиля, который наследуется от стиля MyTextStyle, созданного нами ранее, где мы хотим получить красный текст, используйте следующий способ:

Как видите, нам не пришлось использовать атрибут parent в теге style, потому что имя стиля начинается с имени MyTextStyle (созданный нами стиль). Теперь наш стиль наследует все свойства от стиля родителя, при этом мы изменили одно свойство android:textColor, чтобы текст выводился красным цветом. Вы можете ссылаться на новый стиль через конструкцию @style/MyTextStyle.Red.

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

Итак, мы наследовались от стилей MyTextStyle и MyTextStyle.Red, а затем добавили новое свойство android:textSize.

Не забывайте, что данная техника наследования применима только к собственным стилям. Для наследования системных стилей типа TextAppearance необходимо использовать атрибут parent.

Свойства стиля

Разобравшись с созданием стилей, рассмотрим различные свойства, определяемые в элементе item. Мы уже встречались с такими свойствами, как layout_width и textColor. На самом деле свойств гораздо больше.

Для поиска свойств, которые применимы к заданному View, можно обратиться к документации и просмотреть все поддерживаемые свойства. Так все атрибуты, перечисленные в таблице атрибутов класса TextView могут быть использованы для элементов TextView или EditText. Например, у данных элементов есть свойство android:inputType:

Но вместо этого мы можем также создать стиль для элемента EditText, который будет включать в себя данное свойство:

В файле разметки теперь можно написать так:

На первый взгляд вам возможно покажется, что подобный подход отнимает слишком много времени. Но в больших проектах повторное использование стиля поможет вам сэкономить и время и силы.

Для просмотра всех существующих стилей вы можете посмотреть исходники Android. Найдите папку, в которую вы устанавливали Android SDK, там можно найти нужные исходники. Например, у меня путь к исходникам стилей Android API 17 выглядит следующим образом: D:\Android\android-sdk-windows\platforms\android-17\data\res\values\styles.xml. Помните, что все объекты View не поддерживает сразу все существующие атрибуты, поэтому используйте только специфичные стили для выбранного элемента. Но если вы по ошибке зададите ошибочный стиль для View, то это не вызовет краха приложения. Элемент View будет использовать только подходящие свойства и игнорировать чужие для него свойства.

Существуют также свойства, которые не поддерживаются ни одним элементом View и применимы только как тема. Подобные стили действуют сразу на всё окно, а не на отдельный элемент. Например, есть тема, скрывающая заголовок приложения, строку состояния или изменяющая фон окна. Подобные стили легко определить по слову window, с которого начинается название стиля: windowNoTitle, windowBackground (о них ниже).

Не забывайте использовать префикс android перед именем в каждом элементе item: <item name="android:inputType">.

Отдельно стоит отметить создание стиля для кнопки. У кнопки есть несколько состояний — обычное, в фокусе, нажатое, нажатое с фокусом. Поэтому для кнопки нужно создать четыре отдельных стиля, чтобы кнопка выглядела профессионально.

Извлечение свойств в стили

Если вы решили в своём проекте использовать стили и вам нужно быстро переместить нужные атрибуты, то Android Studio предлагает быстрый механизм для этой операции. В текстовом режиме ставите курсор на названии компонента, например, ImageView, затем щёлкаете правой кнопкой мыши и выбираете Refactor | Extract | Style. . В диалоговом окне выбираете нужные атрибуты для переноса в стили и выбираете имя стиля.

Динамическое изменение стилей

Ни разу не приходилось пользоваться, но вдруг пригодится.

Тема — это более ёмкое понятие. По существу, тема — стиль, который относится ко всему экрану активности или приложению, а не к отдельному компоненту приложения. Таким образом, тема имеет свои атрибуты и свою область применения.

Темы похожи на определения стилей. Точно так же, как стили, темы объявляются в XML-файле элементами <style>, и ссылаются на них тем же самым способом. Различие состоит в том, что тема добавляется ко всему приложению или к отдельной активности через элементы <application> и <activity> в файле манифеста приложения, т. к. темы не могут быть применены к отдельным компонентам.

Чтобы установить тему, откройте файл AndroidManifest.xml и отредактируйте тег <application>, чтобы он включал в себя атрибут android:theme с указанием имени стиля:

Если вы хотите, чтобы тема относилась не ко всему приложению, а к отдельной активности, то атрибут android:theme нужно добавить в тег <activity>.

Во многих случаях нет необходимости придумывать свои стили и темы, так как Android содержит множество собственных встроенных тем. Например, вы можете использовать тему Dialog, чтобы окно приложения выглядело как диалоговое окно (Смотри выше).

Если вам нравится тема, но несколько свойств всё-таки хотите подправить под себя, то просто добавьте тему как родительскую тему к своей теме. Например, мы хотим модифицировать стандартную тему Theme.Light, чтобы использовать свои цвета.

Теперь мы можем использовать свой стиль вместо Theme.Light в манифесте:

Небольшой список свойств, которые используются для настройки собственных тем.

  • android:windowNoTitle: используйте значение true, чтобы скрыть заголовок
  • android:windowFullscreen: используйте значение true, чтобы скрыть строку состояния и освободить место для приложения
  • android:windowBackground: ресурс цвета или drawable для фона
  • android:windowContentOverlay: Drawable, который рисуется поверх содержимого окна. По умолчанию, это тень от строки состояния. Можно использовать null (@null в XML-файле) для удаления ресурса.

В Android 5.0 появились новые темы, которые получили название Material Design.

  • @android:style/Theme.Material (тёмная версия)
  • @android:style/Theme.Material.Light (светлая версия)
  • @android:style/Theme.Material.Light.DarkActionBar (светлая версия с тёмным заголовком)

В Android 9.0 темы Material Design продолжили развитие, они будут активно внедряться в ближайшее время.

  • Theme.MaterialComponents
  • Theme.MaterialComponents.NoActionBar
  • Theme.MaterialComponents.Light
  • Theme.MaterialComponents.Light.NoActionBar
  • Theme.MaterialComponents.Light.DarkActionBar

Для Material Design были разработаны новые атрибуты тем.

  • android:colorPrimary: основной цвет для интерфейса программы — панель, кнопки и т.д.
  • android:colorPrimaryDark: цвет для системных элементов — строка состояния
  • android:colorAccent: Цвет по умолчанию для компонентов, которые находятся в фокусе или активны
  • android:colorControlNormal: Цвет для неактивных компонентов
  • android:colorControlActivated: Цвет для активных компонентов
  • android:colorControlHighlight: Цвет для нажатых элементов интерфейса
  • colorSwitchThumbNormal: и т.д. изучаем документацию

Позже были добавлены другие атрибуты: colorPrimaryVariant, colorOnPrimary, colorSecondary, colorSecondaryVariant, colorOnSecondary, colorError, colorOnError, colorSurface, colorOnSurface, colorBackground, colorOnBackground.

Настройка цветов происходит по определённым правилам. На сайте http://www.google.com/design/spec/style/color.html# есть таблица цветов. Обратите внимание на числа слева. Основным цветом (colorPrimary) считается цвет под номером 500, он идёт первым в таблицах. Этот цвет должен использоваться в качестве заголовка (Toolbar).

Допустим, мы делаем специальное приложение для рыжего кота. Создадим новый файл res/values/colors.xml. На указанном сайте находим таблицу цветов оранжевого цвета Orange и будем использовать предлагаемое значение.

Зададим основной цвет.

Для строки состояние, которая находится выше заголовка приложения, нужно использовать цвет со значением 700 (colorPrimaryDark). Это более тёмный цвет и позволяет различать заголовок приложения и строку состояния. Возвращаемся к оранжевой таблице цветов, запоминаем значение цвета и прописываем его в ресурсах.

Пропишем в теме приложения новые элементы.

На старых устройствах цвет строки состояния не изменяется. Цвет заголовка поменять можно.

Material

В файле res/values-v21/styles.xml для новых устройств нужно повторить указанные действия с небольшой поправкой. В API 21 уже есть предопределённые константы для эти цветов, поэтому используем в именах android:colorPrimary и android:colorPrimaryDark.

Читать:
Как убрать крестик в экселе

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

С главным цветом есть одна тонкость. Старые устройства используют ActionBar и его цвет подчиняется правилам Material Design из коробки. На новых устройствах для активности используется тема без панели действий Theme.AppCompat.NoActionBar и вручную добавляется компонент Toolbar. Чтобы он использовал основной цвет, используйте правильный стиль для фонового цвета.

Третий важный цвет для использования в приложениях — акцентированный. Данный цвет может использоваться для кнопки Floating Action Button и для различных компонентов. Он должен быть достаточно контрастным по сравнению с основным цветом. Для примера выберем зелёный цвет по цвету глаз рыжих котов. Находим в таблице зелёный цвет и выбираем нужное значение из A400

Прописываем цвет в обоих темах:

Сейчас акцентированный цвет мы нигде не увидим. Вернёмся к нему позже.

Акцентированные цвета поддерживаются многими компонентами из коробки. Для некоторых следует использовать аналоги из библиотеки AppCompat:

  • Флажки и переключатели
  • SwitchCompat вместо Switch
  • Курсор у EditText
  • Текст у TextInputLayout
  • Текущий индикатор у TabLayout
  • Выбранный элемент у NavigationView
  • Фон у FloatingActionButton

Пользуйтесь сервисом Material Design Color Palette Generator для создания палитры в стиле Material: выбираем основной цвет, цвет «плавающей» кнопки и сайт генерирует необходимую палитру.

В Android 5.0 появился новый атрибут темы colorEdgeEffect. Вам необходимо переопределить тему, а затем применить к компоненту.

Темы для диалоговых окон

По умолчанию, диалоговые окна на Lollipop-устройствах будут выглядеть в стиле Material Design. Но если вы хотите немного изменить внешний вид, то можно применить стили и темы к ним. Создайте отдельный стиль:

Добавьте созданный стиль к теме.

Также можно создать отдельный стиль для негативной кнопки, чтобы она была красной и отличалась от позитивной кнопки.

Затем в коде используете созданный стиль.

Сам пока не проверял.

Темы для диалоговых окон для старых устройств

В библиотеке совместимости версии 22.1.0 появилась поддержка Material Design для диалоговых окон.

Для начала вызовем диалоговое окно стандартным способом:

Добавим стили в файл styles.xml:

Для вывода диалогового окна будем использовать класс из библиотеки совместимости, у которого есть дополнительный параметр для указания темы.

Если хотите также поменять цвет для заголовка диалогового окно, то добавьте в предыдущую тему AppCompatAlertDialogStyle новый элемент windowTitleStyle и создайте стиль для него.

Стили для компонентов

У компонентов также появились новые стили, связанные с Material Design. Например, TextAppearance.Material.Title:

Темы для компонентов

Обычно темы применялись к активности или приложению. Сейчас самый распространённый вариант Theme.AppCompat.

В Lollipop и AppCompat с версии 22.1 стало возможным присваивать тему отдельному компоненту. В этой связи появился отдельный тип темы ThemeOverlay, который позволяет менять только необходимые настройки. Например, ThemeOverlay.AppCompat.Light меняет фоновый цвет, цвет текста и выделенный текст, как если это была бы светлая тема. Соответственно, ThemeOverlay.AppCompat.Dark работает как тёмная тема.

Это может пригодится, чтобы цвет текста не совпадал с цветом фона и был читаемым. Например, это часто используется у Toolbar:

Также используется при создании собственных тем

Выбор темы в зависимости от версии платформы

Каждая новая версия Android обзаводится несколькими новыми темами. И, возможно, вам захочется использовать новые темы в своих приложениях, чтобы пользователи новых аппаратов увидели современный интерфейс, при этом владельцы старых аппаратов будут видеть приложение в другом виде.

Предположим у вас есть собственная тема, использующая стандартную светлую тему, в файле res/values/styles.xml:

Чтобы задействовать также новую голографическую тему, доступную в Android 3.0 (API Level 11) и выше, создайте альтернативный файл стилей в папке res/values-v11, где будет указана новая тема:

Для последней версии Android 5.0 вам понадобится папка res/values-21 для темы, использующую Material Design.

Теперь программа автоматически будет переключаться между стилями, самостоятельно определяя версию Android.

Список стандартных атрибутов, используемых в темах, можно найти на странице R.styleable.Theme .

Использование стилей и тем платформы

Вы можете создавать собственные стили, а можете подключать готовые системные стили или отдельные атрибуты стилей, используемых в Android. Для указания стиля, предопределённого в Android, используется следующий синтаксис:

Знак ? применяется для поиска значения стиля в текущей теме, а подстрока ?android означает поиск значения стиля в системной теме Android.

В студии можно выбрать системную тему сразу из среды разработки. Откройте файл разметки в режиме Design. Чуть выше формы имеется выпадающая кнопка AppTheme. Нажмите на неё и поиграйтесь со списком, чтобы просмотреть другие варианты. Вы сможете увидеть, как будет выглядеть ваше приложение в разных темах. Учтите, что эта настройка не вносит изменения в ваш файл, а предназначена только для просмотра темы, чтобы вы представляли, как будет выглядеть программа у разных пользователей.

В последних версиях проектов студии, которые используют тему AppCompat для создания полноэкранной активности используйте стиль:

И примените его к нужной активности.

Новые темы в Android 4.4

В Android 4.4 появилась возможность сделать панель навигации и строку состояния полупрозрачными. Откройте файл styles.xml и добавьте строчки:

Последний пункт у меня закомментирован. Он позволяет настроить тему для ActionBar. Можете поиграться с ним. Для сравнения ниже представлены скриншоты стандартного окна активности с чёрными полосками снизу и сверху и стилизованной активности. Для наглядности я выбрал оранжевый цвет для фона активности.

Theme in KitkatTheme in Kitkat

Если говорить об эволюции тем и стилей, то в Android 2.x темы были в зачаточном состоянии. В Android 3/4 дизайнеры проделали огромную работу, чтобы система стала красивой и предложили тему Holo. В новой версии Android 5.0 работа над стилями была продолжена и была представлена новая концепция стиля под названием Material Design с подробной документацией по её использованию.

В статье Android App Launching Made Gorgeous рассматривается интересный случай, когда неправильное использование тем приводит к некрасивому эффекту — сначала загружается пустой экран, а затем уже экран вашей активности.

Темы для View

В статье говорилось, что отдельные компоненты должны использовать стили, а активности — темы. В Android 5.0 Lollipop, а также старые устройства с API 11 через библиотеку совместимости AppCompat могут также использовать темы:

Небольшой список на память.

  • ThemeOverlay.AppCompat
  • ThemeOverlay.AppCompat.Light
  • ThemeOverlay.AppCompat.Dark
  • ThemeOverlay.AppCompat.ActionBar
  • ThemeOverlay.AppCompat.Dark.ActionBar

Например, ваши компоненты в разметке используют светлую тему, а родительский элемент должен использовать тёмную тему. Тогда применим к нему готовую тему.

Если вам нужно изменить конкретный атрибут, например, colorAccent, то добавьте новую тему:

Примените тему к вашему компоненту через android:theme=»CustomAccentOverlay». Так вы можете переопределить и другие атрибуты.

Общие советы

Избегайте конкретных значений для цвета.

Лучше используйте атрибуты, что позволит вам корректно переключаться к тёмной теме.

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

При работе с элементами темы программным способом не используйте Context от Application, только от Activity.

1. Introduction

This is a continuation of the Article Android Design System and Theming: Typography. In that article I explained why having a Style System help us to have a cohesive and easy to develop UI in our apps. I used typography as a guide to explain the main concepts related to the Android Application Theming, the Android solution to have a Style System.

In this article, I will follow a similar structure, but now I will explain a much noticeable aspect of our apps: Colors.

  • We will see first how to properly name colors in 2. Color naming
  • Then we will see the most important theme attribute for color 3. Color theme attributes and how to apply them in our theme. 4. Update your theme with your colors
  • After that, we will see how the widgets behave with the theme colors. 5. Widgets and default attributes.
  • Later on, we will apply different themes to our app in 6. I need more Themes and add custom theme attributes. 7. What if 12 attributes are not enough
  • And finally we will see some extra points in 8. Extra

Material Design Documentation is being updated constantly. Some of the information here presented might be slightly different in new Material Design versions.

2. Color naming

First of all, we have to select our colors. As far as in Android Studio 4.0.1 (In 4.1 is fixed﹡) if you create a new project with the empty activity wizard, the colors file looks like this.

We should change it.

As it is recommended the colors should have literal names (describe the value not how it’s used). To help you with color naming you can use the Material colors style, use a tool like name-that-color or, a Plugin like this one.

I will use these.

Now that we have our colors we have to set them in our theme attributes.

﹡In Android Studio 4.1, the new project wizard creates the colors with literal names.

You can learn about theme attributes in my previous post in the section Theme attributes in less than 100 words.

3. Color theme attributes

An image is worth 1000 words.

color-attributes

Here we can see the 12 most important color attributes that the Material Design Library offers us.

When creating your Theme you don’t need to change all of them. Start changing only the Primary and Secondary and their cousins ( variant and on ). The rest of the attributes will, most of the time, do the job.

As you can see the color attributes are divided into some colors like colorPrimary , and in how should the foreground of that color be, like colorOnPrimary .

This is very helpful because we have now one place where we define our colors and also how the foreground of that color is, so we can be confident that there won’t be visibility problems. Like if a dark-colored button has a dark-colored text.

There is an intrinsic relation between primary , variant and on . If you change one of them you should verify that everything keeps looking good between each other.

You can read more about common theme attributes in the Google Developers Blog Post from Nick Butcher Common Theme Attributes

4. Update your theme with your colors

Now that we have our colors set, let’s apply them to our Theme.

First of all and in Android Studio 4.0.1 (In 4.1 is fixed﹡) the Empty Activity wizard creates this style:

We will clean this up.

First, make the parent inherit from a Material Design theme. I will use Theme.MaterialComponents.DayNight.DarkActionBar

Don’t forget to add the libray com.google.android.material:material:<latest_version> in your gradle module file.

Second, change the name to reflect that it is a theme.

In section 8.1. Use a Base Theme you can see a better approach when having a less simple themes hierarchy.

Finally, move it to a themes.xml file.

﹡In Android Studio 4.1, the new project wizard, the theme is already created in the themes.xml file.

4.1 Note about naming and files:

4.1.1 Naming Styles

Because there is no XML tag <theme> we have to use the <style> tag for themes and styles indistinctly. Therefore to not getting confused with our design system, we need a convention to name them.

For Themes and Widget Styles the convention is:

  • Use Theme.YourAppsName.ThemeVariantName for the themes
  • Use Widget.YourAppsName.WidgetType.WidgetVariantName for the widget
  • Themes will be set for a theme in an XML.
  • Widgets will be set for a style in an XML.

With this, it is easy to see that we are not using themes when we should use styles, and vice versa.

4.1.2 Naming Files

  • Add your themes in the themes.xml file
  • Add your widget styles in the styles.xml file

Now if we run our app we can see how the colors are applied as we defined them in the theme.

5. Widgets and default attributes.

One of the main advantages of using theming is how easy they work with widgets.

You might be tempted to create a style for the buttons with your attr/colorPrimary and attr/colorOnPrimary . You don’t need that.

Android System and MD Library will do all for you. This will be shown equally. The button content color is set to colorPrimary and colorOnPrimary for the text, so you don’t have to do anything.

The Material Design website has all the information about theme attributes so is very easy to understand and modify how they work.

Here is an extract of the Container Attributes of the Contained button Component Docs

Button theme attributes

The Material Design Library specifies different styles for the different components.

For example, the Button widget has 3 different styles. Contained, Text, and Outlined. These styles use theme attributes to define their look and feel. We can just change our theme attributes and set the specific Material Design style to accomplish a robust Design System in our app.

Check how the Contained Buttons does not need any specification to be painted with the theme colors, and how the others just need to set the style to a Material Design Library Style.

Note how the Outlined Button Style is set by a theme attribute called materialButtonOutlinedStyle . There is also a borderlessButtonStyle attribute for the Text Button, but as of today, the official Material Docs shows the snippet above.

There are many other theme attributes defined in the MD library, and updates in the official documentation occur regularly. Is a good practice to review them while developing.

Android engineers recommend using Material Design Components. You can read more about it in this Android Developers post:: We Recommend Material Design Components

There are a couple of places where this can be more complicated than it looks, but most of the time you won’t have problems.

Check the companion app to see how some widgets are painted just defining a theme and letting the Android and the default values do the rest.

Widgets

5.1. Widget Customization

In case you need to customize a widget, start from the Base Material Widget, and create a specific style for it.

As mentioned before in 4.1.1 Naming Styles, name the styles with the Widget. prefix as best practice.

5.2 Widget Customization with Widgets Theme Attributes

There are many theme-attributes related to Material Widgets, like buttonStyle , appBarLayoutStyle and bottomNavigationStyle . You can set these theme attributes in your theme to a specific style, and forget about setting the style in the view.

With this technic, we avoid adding styles directly in the view and reduce the risk of adding a wrong one.

6. I need more Themes

Your app might have different versions like Free and Premium and you want to have different looks between both. Another scenario is that your application uses different color schemes on different screens. In these cases, you can have more than one theme.

Because your application has the theme set up in the manifest, to select a different one in an activity or fragment you will need to do it programmatically.

For an activity is as easy as calling setTheme(R.style.yourTheme) before calling setContentView()

In a fragment, setting the theme programmatically is done like this:

Note 1: If you need to change your theme after views are instantiated you will need to call recreate() to inflate the views again with the new theme.

Note 2: Notice how the dots are replaced with underscores when accessing the theme from the resources. Theme.MyApp.Alternative in the themes.xml will be Theme_MyApp_Alternative in your Activity or Fragment.

Check it live in the companion app: ThemeAlternativeFragment.kt

6.1. Theme Overlays

There are times that you need to change the theme but only in a fraction of your view hierarchy. For that, there is the Themes Overlays technic. This topic was already covered in my previous post.

Here is an excerpt:

In any of your views, you can add the android:theme attribute and set it to a specific theme. The view and all its children will use the new theme. ThemeOverlays inherit from an empty parent, should define as few attributes as possible, and its name should start with ThemeOverlay , thus it’s clear its purpose.

As you can see in the sample app I had to change the background in the layout android:background=»?attr/colorSurface» so it gets the proper surface color in the background. Also, I needed to change the text color in the style.

Depending on your necessities you will have to tweak little some attributes, but most of them will work properly.

Theme Overlays

6.1.2 Premade overlays

The Material Design Library provides some premade overlays. Like ThemeOverlay.MaterialComponents.Dark Before you build your own, is good to check if some of them already comply with your requisites.

You can read more about theme overlays in the Google Developers Blog Post Android Styling: themes overlay

7. What if 12 attributes are not enough?

One of the powers of theming is the ability to change the whole UI styles easily. Imagine this scenario: your app has 2 themes for normal and premium users. The primary color is different for both, just creating a new theme with a different primary color and changing the theme for each of the user types will be sufficient.

Now imagine that our design team wants a specific FAB button color for the premium members, which is not the same as the premium secondary color. In this case and because FAB buttons use colorSecondary attribute to tint it, we need a solution.

We can define a custom theme attribute that will be used to tint the fab buttons, instead of the default attribute (in this case colorSecondary ).

ALT THEME

You can see in the images above how the EXTENDED FAB is colored as a default Fab Button using the secondary color on both screens. But for the CUSTOM ATTRIBUTE button, it used the secondary color (default behavior) in the base theme (left), but it uses the orangePremium color, set in the theme attribute fabBackgroundColor for the alternative theme(right).

You can check it in the companion app tab: Alt.Theme

8. Extra

8.1. Use a Base Theme

It is a good practice to have a Base Theme where you add things that won’t change for any theme, like text appearances, shapes or widgets default styles, and create specific themes inheriting from it.

8.2. Dark Theme

Dark Theme is a big topic that will fit best in a different post. But to give it a try in your app you can do these simple steps:

  • First create a file in res/values-night and call it theme.xml
  • Secondly, create a theme with the same name as your primary theme name (the one you set in the manifest). You can simply copy and paste it.
  • Third, change the basic colors for the Dark Mode. To start, use the same ones you have in the light theme but with lower saturation.
  • And finally, copy and paste this code to add a button to toggle the Dark Mode in your app.

The important part is the one inside the setOnClickListener The rest is to give a plug&play option.

Now you can see your app in dark mode with the default values.

There is much more to talk about Dark Themes but this post is already big enough. Let’s do it in another one.

8.3. PrimarySurface

colorPrimarySurface is a theme attribute (and a variant of some styles) that helps while working with surfaces in Dark Mode.

Several colored widget surfaces are set to the primary color. Like the Toolbar or Bottombar, but in case we change the theme to a Dark Theme, the primary color as the surface color does not look appropriate.

For these cases there are colorPrimarySurface and colorPrimaryOnSurface . Widgets can use these attributes as backgroundTints so in Light Theme the primary color will be used, but in Dark Themes a dark surface color will be selected.

We can see this behavior in the BottomBar style. In the companion app,the BottomBar style is Widget.MaterialComponents.BottomNavigationView.PrimarySurface . When we turn on the Dark Mode the BottomBar will be colored as dark grey.

If we instead used Widget.MaterialComponents.BottomNavigationView.Colored when the Dark Mode is turned on, the BottomBar will be colored as primary.

Bottom Sheet Styles

9. Recap

There are only 4 steps to have your app theme up and running.

  1. Add your primary and secondary colors to your colors.xml file. (Use literal names)
  2. Create your theme in the themes.xml file and reference it in your manifest.
  3. Reference the main color theme attributes ( primaryColor , primaryVariantColor , secondaryColor . )to your preferred ones.
  4. Use the Material Design Widgets in your layouts, and adapt them using styles in case you need specific customization.

10. Conclusions

Android Theming is a powerful technic that can help us to have a cohesive UI and speed up our development.

The topic is big, and there are many things to learn, but to have a base theme is straight forward and as you saw in the recap section there are only 4 easy steps. (In Android Studio 4.1 the first 3 steps are already done in new projects)

If you haven’t yet, you can check my previous article Android Design System and Theming: Typography. And as I mentioned there, the general topics here presented can be applied also to text appearances and shapes.

Before saying goodbye I recommend you checking this Android Dev Summit talk Developing Themes with Style by Nick Butcher and Chris Banes. There are also several posts in Android Developers Medium by the Android Design Team covering all topics about theming and styling.

Finally, I hope this article helps you to understand Android Theming and Styling a bit better.

What is the difference between colorPrimary and colorPrimaryDark in themes

I’m trying to understand how the theme works in android. I don’t know why colorPrimaryDark won’t work with me or maybe i’m doing it wrong.

I tried this set and my action bar turns red because of colorPrimary:

I tried to remove the colorPrimary and it turns black (which I thought it will use blue because of colorPrimaryDark:

I tried to remove the colorPrimaryDark and left the colorPrimary and it turns red again:

I don’t know if i’m using it in wrong way or it’s not really changing at all. Can anyone tell me the difference among them?

Похожие статьи