Android studio java shape

Drawable. Фигуры и градиенты

Shape и ShapeDrawable

Фигуры являются подмножеством Drawable-ресурсов.

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

Можно создавать ресурсы фигур на основе стандартных фигур вроде прямоугольника, эллипса, линии. Для использования ресурсов фигур нужно создать в подкаталоге res/drawable XML-файл, в котором будет присутствовать тег , который в свою очередь может содержать дочерние элементы , ,

Имя файла без расширения будет служить идентификатором (ID): R.drawable.filename в Java-коде и @[package:]drawable/filename в XML-файлах.

Элементы фигуры

— отступы. Возможные атрибуты: android:left, android:top, android:right, android:bottom

  • — размеры фигуры. Возможные атрибуты: android:height, android:width
  • — сплошной цвет для фигуры. Возможные атрибуты: android:color
  • — контур фигуры. Возможные атрибуты: android:width, android:color, android:dashGap (расстояние между черточками), android:dashWidth (длина пунктирной черточки)
  • rectangle (Прямоугольник)

    shape_rect.xml — Атрибут android:shape здесь необязателен: rectangle — это значение по умолчанию.

    Пример с градиентным прямоугольником в качестве разделителя

    Создадим файл separator.xml:

    В разметке приложения добавим код:

    У первого разделителя ширина 1dp, у второго — 3dp. Получили красивую полоску.

    У прямоугольников можно скруглить углы при помощи тега corners

    Можно закруглить углы по отдельности:

    oval (Эллипс)

    Другой вариант с пунктиром:

    ring (Кольцо)

    shape_ring.xml — Для кольца имеются дополнительные атрибуты:

    innerRadius Внутренний радиус innerRadiusRatio Отношение между внешним и внутренним радиусами. По умолчанию равно 3 thickness Толщина кольца (т.е. разница между внешним и внутренним радиусами) thicknessRatio Отношение ширины кольца к его толщине. По умолчанию равно 9

    line (Горизонтальная линия)

    shape_line.xml — Линия может быть только горизонтальной

    Градиенты: gradient и GradientDrawable

    Тег gradient (класс GradientDrawable) позволяет создавать сложные градиентные заливки. Каждый градиент описывает плавный переход между двумя или тремя цветами с помощью линейного/радиального алгоритма или же используя метод развертки.

    Тег gradient внутри тега shape. Основные атрибуты: type, startColor (обязателен), endColor (обязателен) и middleColor (необязателен). Также иногда оказывается полезным атрибут centerColor.

    Используя атрибут type, вы можете описать свой градиент:

    linear

    • android:type=»linear» можно опустить, он так и есть по умолчанию. Отображает прямой переход от цвета startColor к цвету endColor под углом, заданным в атрибуте angle.
    • Атрибут android:angle используется только линейным градиентом и должен быть кратным значению 45.

    Дополнительный материал: Android Dev Tip #3 — помните о прозрачности, который может привести к другому результату.

    Также можно задействовать атрибуты centerX и centerY.

    radial

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

    sweep

    Рисует развёрточный градиент с помощью перехода между цветами startColor и endColor вдоль внешнего края фигуры (как правило, кольца).

    Читайте также:  Unable to resolve target android 19

    Можно использовать атрибуты android:centerX и android:centerY.

    Попробуйте также такой вариант.

    А почему бы не повращать?

    Примеры с shape

    Закругляем уголки у компонентов

    Создадим отдельный файл res/drawable/roundrect.xml и с его помощью скруглим уголки у LinearLayout, ImageView, TextView, EditText:

    В разметке активности пишем следующее:

    Овальный кабинет

    В Белом доме есть Овальный кабинет. Если вам придётся писать приложение для администрации президента США, то все элементы нужно сделать овальными. Создадим файл res/drawable/oval.xml:

    Заменим в предыдущем примере android:background=»@drawable/roundrect» на android:background=»@drawable/oval».

    Источник

    Android studio java shape

    Android Shape Drawable Examples

    February 27, 2018

    In Android, shape drawables can be defined in xml which can be used as resources in java code and xml to set image related attributes such as background, icon, etc of views. You can define rectangle, oval, ring, and line shape drawables in xml.

    The root element of the shape drawable xml is shape, you can define corners, gradient, padding, size, solid and stroke as child elements of the shape to define a drawable. Using corner element, you can define round cornered rectangle shapes. Gradient element allows you to set start color and end color, x position, y position, gradient type and angle in multiples of 45 to define gradient of the shape. Solid element allows you to set color to fill the shape. Stroke element allows you define stroke like and its thickness.

    You need to save shape drawable xmls in res/drawable folder. See android resources tutorial for more information on android resource and accessing resources.

    Rectange Shape Drawable

    Below example defines rectangle shape drawable with gradient and round corners. Attributes of the gradient element lets you define center of gradient on x and y axis, angle of gradient 0(left to right), 45 or 90(bottom to top), start, end and center colors and type of gradient (radial, linear and sweep).

    When above drawable is applied to a button by setting background attribute to the drawable, it will create round cornered, color-gradient button. Below is the output with sweep, linear and radial gradient types.

    Below is the output with centerX and centerY values of gradient element set to 0.1 and 0.5, 0.5 and 0.1 and 0.5 and 0.5 for different gradient types.

    Below is the output with centerX and centerY values of gradient element set to 0.1 and 0.5, gradient type set to linear and with different gradient angles.

    Below is the output with different values for gradientRadius attributes of gradient element and with gradient type set to radial.

    Below is the shape definition with stroke element, you can use it to create button with border as shown below.

    Oval Shape Drawable

    You can create oval shape drawable as shown below and apply it to button to create oval shaped button.

    Below picture shows oval shaped buttons which you can get when background is set to oval shaped drawable with solid or gradient elements defined.

    Читайте также:  Engineering test debugging пароль android 2din

    Ring Shape Drawable

    To create ring shape drawable, you need to set shape, innerRadius and thichkness attributes of shape element. Below screen shows round buttons which you can create by setting background attribute of a button to ring shape drawable.

    To adjust the ring around view, you need to set padding in the definition of ring shape drawable. You can set ring color using solid or gradient elements of shape.

    Below are shape drawable xmls for all three button outputs shown above respectively.

    Line Shape Drawable

    To define line shape drawable, you need to set shape attribute of shape element to line and add storke element with color and size element.

    About

    Android app development tutorials and web app development tutorials with programming examples and code samples.

    Источник

    Android Shape, Selector Examples

    Shape, selector, and layer-list are usually used to create custom drawable resources in android development. Those three XML elements can save a lot of UI resources and time if being used properly. This article will show you how to use them correctly.

    1. Custom Drawable File Overview.

    1. All the three XML elements should be defined in an XML file under the app/res/drawable folder. The file name is just the drawable resource id.
    2. For example, if app/res/drawable/my_layer_list.xml is just the file. Then you can refer to it in both java code or other XML files.
    3. Refer to the my_layer_list.xml in Java Code: R.drawable.my_layer_list.
    4. Refer to the my_layer_list.xml in Xml Code : Android:background=”@drawable/my_layer_list”.

    2. Shape.

    The shape is used to define custom shapes in android drawable resources. It is used in both selector and layer-list elements. It has the below properties.

    1. Android:shape : Value can be “line“, “rectangle“, “oval” or “ring“.

    2.1 Shape’s Sub Element.

    2.1.1 .

    1. The gradient XML element is used to define color gradual change style. It has the below attributes.
    2. Android:startColor: Start color value.
    3. Android:endColor: End color value.
    4. Android:angle: Gradient angle, 0 means from left to right, 90 means from bottom to top, the value should be an integer that is multiple of 45, the default value is 0.
    5. Android:type: linear, radial, and sweep.
    6. Below is an example of the gradient XML element.
    7. Below is the above example’s XML source code.
    1. The solid XML element is used to define shape internal fill color. It will override the attributes effect. It has the below attributes.
    2. Android:color: The color value that is used to fill the shape.
    3. Below is an example of the solid XML element.
    4. Below is the above example’s XML source code.
    1. The stroke XML element is used to define shape bolder style. It has the below XML attributes.
    2. Android:width : Border width.
    3. Android:color: Border color.
    4. Android:dashWidth : Dash border width.
    5. Android:dashGap: Gap between two dashes of the border.
    6. Below is an example of the stroke XML element.
    7. Below is the above example’s XML source code.
    1. The corners XML element is used to define shape corner style. It has the below XML attributes.
    2. Android:radius: The radius of the corner. The bigger the radius value, the round-shaped the corner.
    3. Android:topRightRadius: Top right corner radius value.
    4. Android:bottomLeftRadius: Bottom left radius value.
    5. Android:topLeftRadius: Top left radius value.
    6. Android:bottomRightRadius: Bottom right radius value.
    7. Below is an example of the corners XML element.
    8. Below is the above example’s XML source code.
    1. The padding XML element is used to define the padding values. It has the below XML attributes.
    2. android:top: Top padding value.
    3. android:bottom: Bottom padding value.
    4. android:left: Left padding value.
    5. android:right: Right padding value.
    6. Below is an example of the corners XML element. There are two custom shapes in the below example. The green shape is drawn at the top because it is defined at last in the layer-list definition.
    7. Below is the above example’s XML source code.
    1. The size XML element is used to define the shape width and height value.
    Читайте также:  Новинки андроид для планшета

    3. Selector.

    The selector is used to define the view component’s background color or background image by it’s various states.

    3.1 View Component’s State.

    A view component has various state. For example, a button has following states:

    1. android:state_pressed : Boolean value, true means button is pressed, false means button is not pressed.
    2. android:state_enabled : Boolean value, true means button is enabled, false means button is disabled.
    3. android:state_focused : Boolean value, true means button is focused, false means button lost focus.
    4. android:state_window_focused : Boolean value, this is the button default state. It is same as do not specify button state.

    3.2 Selector Definition.

    You should define a selector in a xml file under app / res / drawable folder. Such as my_selector.xml

    You can define several items in the selector definition xml file. Each item include a drawable object (color or image) that will be used for a button state.

    Android system will check each item in the selector by it’s list order, if one item match current button state, then use that drawable object. If no state match, then use default item.

    Please Note : The default state item should be written in the end of the selector xml. If you put it at the beginning of selector xml, no other state will take effect.

    From above example, we can see below default state item at the end of the xml.

    It behaves same as below default state item.

    If we apply above selector drawable to a button as background.

    We can see below screen effect. When the button is pressed, the background color is green, when not pressed the background color change to orange.

    If you can not watch the above video, you can see it on the youtube URL https://youtu.be/t-D2511VoYg

    Above example use some custom color variables, if you do not know, please read How To Define Custom Color Variables In Android Studio.

    Источник

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