- Полный список
- Bitmap
- Layer List
- State List
- Android Layer-List Example
- 1. How To Define Android Layer List.
- 2. Layer-list Three Layer Example.
- 3. Layer-list Image Border Example.
- 4. Layer-list Red Crosshair Example.
- 5. Layer-list Heart Example.
- 6. Layer-list Bitmap Example.
- Programmer Group
- Introduction to Basic Use of layer-list for Android Layer
- 1. What is layer-list? What’s the effect?
- 1.1 What is layer-list?
- 1.2 layer-list uses
- 2. General Principle of Layer-list
- 3. Basic use examples of layer-list:
- 3.1 Effect 1: Single Side Line
- 3.2 Effect 2: Bilateral Line
- 3.3 Effect 3: Shadows
- 3.4 Effect 4: Picture Cascade
- 3.5 Effect 5: Overlay Rotation
- 4. Extended use of layer-list
- 4.1. Implementing the effect of selector
Полный список
— изучаем drawable теги: , ,
Продолжаем разбирать типы Drawable, которые можно описывать с помощью XML-разметки. Проектов в этом уроке создавать не будем. Я просто буду в своем проекте создавать XML-файлы в папке drawable и ставить их фоном для View. А в тексте урока приведу код и скрины. Иногда буду вешать дополнительно серый фон, чтобы был виден реальный размер View.
Чтобы программно добраться до Drawable, который вы для View повесили как фон, надо просто вызвать метод getBackground.
Bitmap
Тег позволяет получить Drawable обертку для Bitmap. У тега есть несколько атрибутов.
В атрибуте src указываем нужный нам файл-изображение.
Атрибут gravity указывает, как bitmap будет располагаться внутри Drawable. Можно использовать несколько значений, разделенных знаком | . Значения тут стандартные, и некоторые из них мы часто используем при работе с layout. Рассмотрим пример.
Значение атрибута gravity сдвигает изображение влево-вверх
Далее ставим следующие значение атрибута gravity:
fill_horizontal — растянуть по горизонтали
fill — растянуть (используется по умолчанию)
Насколько я понял, значения clip_vertical и clip_horizontal идентичны значениям fill_vertical и fill_horizontal в случае когда Bitmap по размеру больше, чем предоставляемое ему пространство. Т.е. clip_vertical сожмет его по вертикали, так чтобы он влез. А clip_horizontal — по горизонтали.
Атрибут tileMode — это режим «плитки». Позволяет замостить вашим изображением все доступное пространство. По умолчанию он имеет значение disabled.
Для примера я создам такой bitmap.
Четыре разных цвета, внутренние границы — сплошные, внешние — пунктиром.
Если tileMode = repeat, то Bitmap будет размножен и займет все доступное пространство
Далее меняем значение атрибута tileMode.
mirror – Bitmap также будет размножен, но при этом он будет чередоваться со своим отражением
clamp – растягивает края картинки на все свободное пространство
Прочие атрибуты тега :
antialias – сглаживание линий
dither – преобразование цветов, если текущей палитры недостаточно для отображения
filter – фильтр при сжатии или растягивании (пример результата использования есть в Уроке 158)
mipMap – использование mip-текстурирования. Про него можно почитать в википедии. Используйте этот режим, если планируете в процессе отображения уменьшать bitmap более чем в два раза.
Мы рассмотрели XML-описание, но вы всегда можете создать этот объект и программно. Java-реализация – класс BitmapDrawable.
Layer List
Мы можем описать Drawable, который будет состоять из нескольких Drawable-слоев. Для этого используется тег , а внутри него теги .
У нас 4 слоя. Три bitmap со стандартной иконкой и одна фигура. Атрибуты left, top, right, bottom позволяют указывать отступы. А в атрибуте id можно указать id этого Drawable-слоя.
Обратите внимание, что важен порядок тегов item. Каждый последующий слой рисуется поверх предыдущего. Например, на получившемся изображении видно, что прямоугольник проходит «над» верхней иконкой, но «под» нижней.
Мы можем в коде получать доступ к отдельным Drawable внутри LayerDrawable. Для этого сначала получаем LayerDrawable.
А затем вызываем метод findDrawableByLayerId(int id) и указываем id, который вы указывали в атрибуте id тега item. На выходе получим Drawable.
Также у LayerDrawable есть еще несколько интересных методов
getDrawable(int index) — возвращает Drawable по индексу, а не по id
getId(int index) — возвращает id по индексу
getNumberOfLayers() — возвращает кол-во Drawable-слоев
State List
Тег позволяет отображать Drawable в зависимости от состояния View. Возможные состояние View можно посмотреть в хелпе. Рассмотрим пример с двумя из них: checked и pressed. На экране будет ToogleButton. Эта кнопка переходит в состояние checked и обратно, если на нее нажимать. А во время нажатия, пока палец касается экрана, кнопка находится в состоянии pressed.
State List позволит нам использовать три разных Drawable для отображения кнопки в трех состояниях: обычное, checked, pressed. Для этого создадим три файла в папке drawable.
Прямоугольник темно-серого цвета. Этот Drawable будем отображать в обычном состоянии кнопки.
Прямоугольник темно-синего цвета. Этот Drawable будем отображать в нажатом состоянии кнопки.
Прямоугольник светло-синего цвета. Этот Drawable будем отображать когда кнопка находится в состоянии checked.
И еще один файл, button_selector.xml:
Этот последний Drawable является селектором. В нем мы используем теги item, в которых указываем для какого состояния какой Drawable использовать
В первом item мы указали state_pressed=true, а значит этот item будет выбран системой когда кнопка будет в состоянии pressed. И экране мы увидим Drawable из этого item, т.е. toogle_button_pressed.
В втором item мы указали state_checked=true, а значит этот item будет выбран системой когда кнопка будет в состоянии checked. И экране мы увидим toogle_button_checked.
В третьем item мы не указали никакого состояния, этот item будет выбран при обычном состоянии кнопки. И экране мы увидим toogle_button.
Учтите, что здесь важен порядок расположения item внутри selector. Т.е. система идет по ним по порядку и выбирает первый подходящий. Если вы третий item, который без явного указания состояния, поставите первым, то система всегда будет останавливаться на нем.
Состояния можно комбинировать, т.е. в одном item вы можете указать несколько разных состояний.
Ставим этот Drawable, как фон для ToogleButton:
В результате, сначала видим обычное состояние
Нажимаем и держим, т.е. состояние pressed
Отпускаем – включился checked
Еще раз нажмем-отпустим — выключится checked и будет снова обычное состояние. Для каждого состояния отображается свой Drawable.
У View, кстати, есть методы, которые позволяют программно управлять состоянием. Это, например: setPressed и setSelected.
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Android Layer-List Example
The android.graphics.drawable.LayerDrawable is a drawable object that manages arrays of other drawable objects in the desired order. Each drawable object in the layer list is drawn in the order of the list, and the last drawable object in the list is drawn at the top.
1. How To Define Android Layer List.
- To define a LayerDrawable object, you need to add an XML file under the app/res/drawable folder. And the file name is just the drawable resource id. In this example, the app/res/drawable/my_layer_list.xml file contains a layer list definition.
- In the layer list definition XML file, each drawable object is represented by a element within a single element. You can add any or sub-elements under the element . You can read Android Shape, Selector Examples to learn how to create shapes drawable in android.
- To use the above layer-list drawable resource, you can use the below methods.
- Call the layer-list drawable resource in java source code by id: R.id.my_layer_list.
- Call the layer list drawable resource in Xml Code: @drawable/my_layer_list.
2. Layer-list Three Layer Example.
There is a button in this example, as shown above, it uses a three-layer layer-list drawable object as the background.
my_layer_list.xml
layout XML code use above layer-list.
3. Layer-list Image Border Example.
Above example add two borders for an image. If you want to left only one border. You can remove element to remove green border, remove element or change
value to 5dp to remove red border.
my_layer_list.xml
4. Layer-list Red Crosshair Example.
There are two-layer in this example. The bottom layer draws the vertical line and the top layer draws the horizontal line. You can adjust the layer item’s top, bottom, left, and right offset to change the crosshair center point.
my_layer_list.xml
5. Layer-list Heart Example.
There are three layers in this example.
- The bottom layer is a blue square that rotates 45-degree rotation.
- The middle layer is a red oval.
- The top layer is a green oval.
You can adjust each layer’s item offset to change the heart border and shape. If you set the same color for both three-layer. You can see a heart picture.
my_layer_list.xml
6. Layer-list Bitmap Example.
By default, all rendering items are scaled to fit the size of the included view. Therefore, placing the image at different locations in the layer list may increase the size of the view, and some of the images will scale accordingly.
To avoid scaling items in a list, use elements within elements to specify drawable objects, and define gravity for some items that are not scaled (such as “center”). The below layer-list do not add gravity attribute for bitmap, so the picture has been scaled.
my_layer_list.xml
If you add android:gravity=”center” attribute for each bitmap in the above layer-list XML file, you can see the below screen effect.
Источник
Programmer Group
A programming skills sharing group
Introduction to Basic Use of layer-list for Android Layer
1. What is layer-list? What’s the effect?
1.1 What is layer-list?
Simply understand, layer is a layer, list is a list, then layer-list is the meaning of layer list. But what level list is it? In fact, layer-list is used to create Layer Drawable, Layer Drawable is one of Drawable Resources, so layer-list creates a layer list, that is, a drawable graph.
1.2 layer-list uses
As mentioned above, layer-list is used to create a list of layers by which special drawable s can be created, such as:
In the Alert Dialog below, we just need to set the top edge of the button and the right edge of the left button (or the left edge of the right button), so we can’t use shapes directly, because shapes are used to draw four borders directly; if you have an artist cut it, it’s a lot less flexible, and it adds app s. Volume; in this case, layer-list is the best choice. Of course, there are many uses of layer-list. Here’s just one example. Please continue to look at the specific use.
2. General Principle of Layer-list
The general principle of layer-list is similar to that of Relative Layout (or FrameLayout), but it is also a layer-by-layer overlay, which is added first. In layer-list, different display effects can be obtained by adding four attributes, such as the top left margin, the bottom right margin and so on, to the bottom layer after controlling.
In the example diagram above, the background of the ok button at the bottom of the Alert Dialog is implemented with layer-list. In this layer-list, the bottom layer uses a shape with a filling color of blue, the upper layer uses a shape with filling color of white, and then controls the top edge distance of the upper layer to the bottom layer of 1dp, thus visually forming a white background with a blue top edge. The specific code continues to look down.
3. Basic use examples of layer-list:
Because layer-list creates drawable resources, like shape selector, it is defined in the drawable folder in res and is also an xml file. When you use it, you use the @drawable/xxx reference in the layout file and the R.drawable.xxx x reference in the code with the shape selector.
Different layers in layer-list are defined using item nodes.
3.1 Effect 1: Single Side Line
In the figure, TextView has only one top edge.
Specific code:
- Create a layer-list graph with a blue top border
Under the drawable directory in the res directory, create an XML file named singleline.xml, and then edit the layer-list details as follows:
- Using the layer-list diagram, set the background to textView
3.2 Effect 2: Bilateral Line
In the figure, TextView has upper and lower edges
Specific code:
- Create a layer-list graph with blue top and bottom edges
- Using the layer-list diagram, set the background to textView
3.3 Effect 3: Shadows
Design sketch:
Specific code:
3.4 Effect 4: Picture Cascade
There are two kinds of effects when the images are stacked. One is the stacking after scaling, the other is the stacking without scaling. The default is the zoom effect. The specific effect and implementation code are as follows:
Figure 1: Scaling effect
Specific code 1:
Or you can use the following code to implement the scaled overlay graph:
Figure 2: No zoom effect
Specific code 2:
3.5 Effect 5: Overlay Rotation
Design sketch:
Specific code:
When rotating, only the starting angle (from degress) is needed.
4. Extended use of layer-list
4.1. Implementing the effect of selector
Major use components: RadioGroup Selector layer-list
1). Effect map:
2. Specific code
Define selector selector selector
In the item node of selector, nest layer-list directly
Of course, you can also write layer-list first, and then quote it.
Be careful:
In the above code, because there is no specific shape, we can omit shape and use color directly. The simplified code is as follows:
Be careful:
In RadioGroup, the id of RadioButton is used to control the selection.
Therefore, if you need to set a RadioButton as the default selection, you must set the RadioButton id.
If the id is not set, the result is that the RadioButton will always be selected.
Posted by PRodgers4284 on Thu, 16 May 2019 12:08:33 -0700
Источник