Android xml gradient background

Полный список

— изучаем drawable-тег shape

Подробно ознакомившись с Bitmap, переходим к другому ключевому объекту графики – Drawable.

Drawable – это абстрактный контейнер для графического объекта. Его главное абстрактное умение – он может нарисовать свое содержимое на предоставленной ему канве. А вот что конкретно он нарисует, зависит уже от реализации. Это может быть, например, тот же Bitmap, если мы используем BitmapDrawable объект. Или это может быть простая геометрическая фигура, если мы используем ShapeDrawable.

Drawable-объекты мы можем создавать сами напрямую в коде. Но для некоторых из них мы можем создать описание в xml-файлах, в папке res/drawable. И когда он нам понадобится, мы укажем id файла, система сама распарсит его и создаст нам нужный объект.

Самое распространенное использование Drawable – это свойство background, которое есть у каждого View. В качестве значения вы можете указать там RGB-цвет или id ресурса из папки res/drawable. Далее система сама по этому значению определит тип и далее:

— если это цвет, то создаст ColorDrawable,
— если это id картинки в res/drawable, то создаст BitmapDrawable
— если это id xml-файла в res/drawable, то распарсит его и вернет соответствующего ему наследника Drawable: StateListDrawable, AnimationDrawable или какой-то другой.

В итоге View получит свой Drawable-объект и сможет его нарисовать.

В общем, как вы поняли, у абстрактного Drawable есть несколько наследников-реализаций и в ближайших уроках мы их рассмотрим. Начнем с тех, которые можно описать в xml. По ним есть отдельная статья в хелпе. Там, правда, есть пара ошибок копипаста, но в остальном все верно.

В этом уроке рассмотрим тег

Project name: P1621_DrawableShape
Build Target: Android 4.4
Application name: DrawableShape
Package name: ru.startandroid.develop.p1621drawableshape
Create Activity: MainActivity

Корневой тег shape и у него же есть одноименный атрибут shape, в котором мы указываем тип фигуры. Мы указали rectangle – это прямоугольник.

Далее, внутри тега shape, идет тег stroke, который позволяет задать нам характеристики линии контура (периметра) фигуры. Мы задаем толщину (width) в 1dp и черный цвет (color).

В ImageView пока ничего не отображаем.

Видим ImageView с серым фоном

Перепишем метод setDrawable:

В качестве drawable будем передавать наш файл shape

ImageView теперь отображает прямоугольник с черным контуром.

Посмотрим, какие еще фигуры нам доступны.

Значение атрибута shape = oval, это эллипс

В нашем случае получился круг, т.к. ImageView квадратный.

Значение line даст нам горизонтальную линию

Есть еще фигура кольцо (ring), но о нем чуть позже.

Вернемся к тегу stroke. Добавим в него параметров.

Ширина – 4dp, цвет – синий. Параметры dashWidth и dashGap сделают линию контура пунктирной. dashWidth задает длину пунктирной черточки, а dashGap – расстояние между черточками

Добавим заливку, для этого используется тег solid

Тег solid имеет атрибут color, который позволяет указать цвет заливки фигуры. Мы указали в нем зеленый цвет.

По умолчанию фигура занимает все доступное ей пространство, но мы можем явно указать ее размер с помощью тега size.

Используем тег size с атрибутами width и height

Фигура теперь размером 100х100 и уже не занимает всю доступную ей площадь.

Учтите, что режим отображения зависит от scaleType y ImageView.

Тег padding позволяет нам задать величину отступа внутри фигуры. Это актуально, например, для TextView. Отступ будет учтен при размещении текста.

Мы указали различные отступы со всех 4 сторон.

Если мы теперь повесим эту фигуру в качестве background для TextView, результат будет таким

В качестве заливки мы можем использовать не один цвет, а градиент из двух или трех. Для этого используется тег gradient.

В теге gradient указываем два атрибута-цвета: startColor и endColor.

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

Градиент вовсе необязательно должен идти слева-направо. Мы можем указать угол направления. Для этого у тега gradient есть атрибут angle

Читайте также:  Android как хранить пароли

В angle указываем угол 225. Угол 0 означает направление слева-направо, 90 – снизу вверх и т.д. Угол должен быть кратным 45.

В результате видим угол справа-сверху налево-вниз.

Тег gradient позволяет указать третий цвет, который вклинится между start- и end- цветами.

В атрибуте centerColor укажем синий цвет, и он в градиенте будет между красным и зеленым.

Градиент может быть разных типов. Мы рассмотрели тип linear, который используется по умолчанию. Есть еще два типа: radial и sweep.

Тип radial даст нам круговой градиент, а в параметре gradientRadius мы должны указать радиус круга.

Мы можем указать точку центра кругового градиента атрибутами centerX и centerY. Значения этих атрибутов должны быть от 0 до 1.

Центра градиента будет в точке (0.2, 0.2), если принять размеры фигуры за единицу.

Теперь посмотрим, как выглядит градиент sweep.

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

Для фигуры прямоугольника мы можем сгладить углы. За это отвечает тег corners.

Атрибут radius позволяет задать радиус закругления сразу для всех углов.

Есть возможность задать свой радиус для каждого угла отдельно.

Кольцо

Нам осталось рассмотреть четвертую фигуру — кольцо. Чтобы его получить, надо в атрибуте shape указать значение ring. Для кольца мы можем настроить два параметра: размер внутреннего радиуса и толщина кольца. Причем, эти два параметра мы можем указывать в абсолютном и относительном выражении.

innerRadius – позволяет указать внутренний радиус, а thickness – толщину кольца. Атрибут useLevel, который нам пока неизвестен, должен быть false, иначе эта фигура у меня не отображалась.

Отобразился круг с внутренним радиусом = 50dp и толщиной = 40dp.

Попробуем указать толщину кольца в относительном значении. Для этого вместо thickness используем thicknessRatio. В этом атрибуте мы указываем во сколько раз толщина кольца будет меньше его ширины.

Ширина кольца = 200 dp, это указано в теге size. thicknessRatio =10, значит толщина кольца = 200 dp / 10 = 20dp.

Теперь укажем внутренний радиус в относительном выражении. Для этого вместо innerRadius используем innerRadiusRatio. В атрибуте innerRadiusRatio указываем во сколько раз внутренний радиус меньше ширины кольца.

Ширина кольца = 200 dp. innerRadiusRatio = 3, значит внутренний радиус кольца = 200 dp / 3 = 67dp.

Как видите, кольцо может занимать не весь свой размер. Это зависит от значений, которые мы задаем для внутреннего радиуса и толщины.

У атрибутов относительного размера есть значения по умолчанию. Т.е. если мы явно не укажем значение для innerRadiusRatio, то по умолчанию он будет равен 3, а thicknessRatio по умолчанию равен 9. Посмотрим, как это выглядит

Мы указали только внутренний радиус. А размер толщины будет вычислен исходя из значения thicknessRatio по умолчанию, т.е. 9.

Теперь не будем указывать инфу о внутреннем радиусе.

Мы указали только толщину кольца, а внутренний радиус будет вычислен исходя из значения innerRadiusRatio по умолчанию = 3.

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

Видим, что кольцо заняло не все 200 dp по высоте, которые мы ему задали в теге size. Почему? Давайте считать исходя из значения по умолчанию.

Внутренний радиус = 200 / 3 = 67. Толщина = 200 / 9 = 22. Т.е. диаметр кольца получается = 22 + 67 * 2 + 22 = 178.

Попробуем подогнать размер кольца под все выделенное ему пространство.

Теперь радиус будет равен 200 / 2.5 = 80, а толщина = 200 / 10 = 20. Диаметр кольца = 20 + 80 * 2 + 20 = 200.

Это видно и на скрине. Кольцо теперь по размеру равно ImageView, т.е. = 200.

Атрибуты абсолютных значений (innerRadius и thickness) имеют приоритет перед относительными (innerRadiusRatio и thicknessRatio).

GradientDrawable

Хоть корневой тег и называется shape, но когда система его распарсит, она создает не ShapeDrawable, а GradientDrawable.

Также, этот объект мы можем сами создать программно.

Перепишем метод setDrawable:

Методы set* позволяют нам установить почти все те же параметры, что и в xml-файле.

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

Т.е. в основном — xml- и java-создание равноценны, но есть некоторые нюансы.

На следующем уроке:

— изучаем drawable теги: , ,

Присоединяйтесь к нам в Telegram:

Читайте также:  Камера с панорамной съемкой для андроид

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

How to Add a Gradient Background to an Android App

Adding a gradient as a background color to your an Android app can add extra interest and style and provide a great user experience.

In this post, I will walk you through the steps of how to add a gradient background to your Android app including code samples.

To add a gradient background to your Android app, you need to do the following.

  1. Create a drawable resource with a selector root element
  2. Add an item, shape, and gradient element to the drawable resource
  3. On the gradient element, set the type of gradient to use and provide the start and end colors
  4. Set the background attribute on the layout resource of your fragment or activity to use the drawable resource

Creating a Gradient Background in Android using a Drawable Resource

In this section of this post, I will go through step by step of how to create a gradient background in Android using a drawable resource.

Create a Drawable Resource with a Selector Root Element

First, we will create a new drawable resource we will use for defining the gradient.

Switch your project in Android Studio into Project mode and navigate into the /app/src/main/res/drawable folder. Right click on the “drawable” directory, hover over the “New” item and select the “Drawable Resource File” item.

Then the “New Drawable Resource File” dialog will appear. Provide a file name for the drawable resource file you will use for the gradient background and set the root element to “selector”. Then press the “OK” button to create the drawable resource file.

For drawable resources in Android, the selector element allows you to define child item elements that are selected based on a particular state. For example, a button could have different child items with different visual characteristics depending on whether the button is currently selected, focused, or pressed.

You should end up with a drawable resource file that contains a single selector element.

Adding an Item, Shape, and Gradient Element to the Drawable Resource

Next, we will make some minor changes the drawable resource file we created in the previous step for the gradient background.

Within the selector element, we will add a single item element. Each option to be selected from a selector is represented by an item element. We will only create a single item element as we do not need to change the appearance of the gradient based on a particular state.

Within the item element, we will add a shape element. The shape element can be used to define different shapes such as rectangles, lines, ovals and rings. It allows you to customize the appearance of the shape by changing characteristics such as the corners, setting a gradient, adding padding, setting the width and height sizes, setting a solid fill color and changing the outline of the shape using the stroke element.

Within the shape element, we will add a gradient element which we will configure in the next step to define the appearance of the gradient we will use for the background.

See a code sample below of a drawable resource file containing the selector, item, shape and gradient elements.

Configuring the Gradient Element in the Drawable Resource

In this part of the tutorial, we will add attributes to the gradient element in the drawable resource we created for the gradient background to configure the appearance of the gradient.

This will involve selecting the pattern of gradient we want to use, setting the colors of the gradient, and setting the positioning, direction, and size of the gradient.

Setting the Gradient Pattern

There are three gradient pattern options to choose from in Android.

The gradient pattern is defined on the gradient element by adding the android:type attribute and setting the value to either “linear”, “radial” or “sweep”.

Читайте также:  Android разделить экрана 2

The linear gradient is the default gradient.

See a sample screenshot of a linear gradient used for a gradient background in Android below.

Sample drawable resource code for the linear gradient pattern.

The radial gradient allows you to define a circular center color of the gradient using the start color attribute. The size of the circle can be defined using the gradient radius attribute.

See a sample screenshot of a radial gradient used for a gradient background in Android below.

Sample drawable resource code for the radial gradient pattern.

The sweep gradient offers a sweeping line gradient.

See a sample screenshot of a sweep gradient used for a gradient background in Android below.

Sample drawable resource code for the sweep gradient pattern.

Setting the Gradient Colors

There are up to three colors that can be defined on a gradient.

  • Start color which is defined using the android:startColor attribute
  • End color which is defined using the android:endColor attribute
  • Center color which is defined using the android:centerColor attribute

These colors are set as attributes on the gradient element and the value can either be a hexidemical value representing a color e.g. “#FFFFFF” for the color white or they can be set using a color resource.

Using a color resource is a good method to use as it allows you to define all the colors you use across your Android app in a single location inside the colors.xml resource file in the /app/src/main/res/values directory to simplify any color branding changes you want to make to your Android app in the future.

See a sample colors resource file below containing three colors.

See a screenshot below of a linear gradient with the start, end and center colors defined.

This linear gradient with start, center and end colors was created using the following code.

It is also worth mentioning there are some great free tools available on the internet that can help you find contrasting colors that are pleasant to look at to use for gradients.

Two tools I like are UI Gradients and Web Gradients.

Screenshot from UI Gradients Screenshot from Web Gradients

Setting the Positioning, Direction, and Size of the Gradient

The center position of the gradient can be changed using the android:centerX and android:centerY attributes. The value of the centerX and centerY attributes is a relative position defined as a Float value ranging from 0 to 1.0.

The angle of the gradient can be set using the android:angle attribute using the Integer value representing the angle in degrees. This value must be a multiple of 45. A value of 0, which is the default value, represents an angle of left to right, a value of 90 represents an angle of bottom to top.

In the case of a radial gradient pattern, the size of the circle in the gradient can be changed using the android:gradientRadius attribute which will accept a Float value.

Setting Background Attribute to use the Drawable Resource

Now that we have finished creating the gradient in the drawable resource file, we will need to update the layout resource file for our Activity or Fragment to the drawable resource for the background.

In your layout resource file for your Activity or Fragment, locate the root layout whether that is a LinearLayout, RelativeLayout, ConstraintLayout, or something else, and set the android:background attribute on the layout to the drawable resource we created.

See a code sample for setting a drawable resource as a background for a ConstraintLayout for the main activity inside the activity layout resource file.

Bonus: A Great Tool to Automate the Creation of Gradient Backgrounds in Android

As I was putting together this tutorial I found a free tool that can speed up this process for generating gradient backgrounds for Android apps.

There is a free to use code generator tool available on the internet called Angry Tools that can be used to generate the code for the drawable resource containing the gradient using the user interface.

Angry Tools – Code Generator for Gradient Drawable Resources in Android

Источник

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