Android layer list image

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

— изучаем 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.

Читайте также:  Android phones and tablets

1. How To Define Android Layer List.

  1. 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.
  2. 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.
  3. To use the above layer-list drawable resource, you can use the below methods.
  4. Call the layer-list drawable resource in java source code by id: R.id.my_layer_list.
  5. 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.

  1. The bottom layer is a blue square that rotates 45-degree rotation.
  2. The middle layer is a red oval.
  3. 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.

Источник

Simplifying layouts with layer-list drawables

a reliable way of positioning drawables within layer-lists

Mar 21, 2016 · 4 min read

I always thought the compound drawable (e.g. drawableLeft) was a nifty feature of the TextView. Unfortunately I remember thousands of times when it wasn’t nifty enough for my needs. There was usually something missing. Something I couldn’t overcome by a proper usage of other attributes (including the drawablePadding).

Читайте также:  Grand santa fe android

I was recently developing an app in which the navigation drawer wasn’t following the Material Design Guidelines 100%. To be honest, only the list items were somehow following the material list-item guidelines.

Adapting NavigationV i ew from the Support Design Library to fit my needs wasn’t really an option for me. Writing the navigation menu from the scratch was going to take much less time. At least I thought that at the moment…

I wanted to create a regular NavigationDrawer list item in the most elegant and easy way possible. Just a text with an icon. As simple as that.

The rest of this post describes my struggle on performing that simple task.

If you’re lucky and you know the exact width of your icons, it should be super-easy. E.g. if your icons for the NavigationDrawer are exactly 24dp wide, this:

should do the job just fine.

But… if you can’t predict the size of the icon, things will probably get a bit uglier. It’s not something unusual, I’ve been there multiple times. The solution I was ending up with, was usually something like this:

It’s working fine, even with icons with different dimensions (as in the example), but I can’t really say that’s an elegant solution. Imagine a layout with 5 or 10 of this sort of list-items stacked on top of each other. There must be a better way!

So I got back to square one (using compound drawable in a TextView) and started messing around with a special drawable.

I thought to myself:

I just have to anchor the icon at the left border of the 72dp space and shift it by 16dp to the right. That doesn’t sound that difficult. I should be able to do that easily with a layer-list!

This is what I came up with:

Two simple layers. The first one that would force the 72dp-wide bounds for the icon. And the second one with the icon itself — shifted. It really worked. It looked promising!

With just a single, simple TextView:

Unfortunately this is what I saw on a random Samsung device with 4.X Android:

It wouldn’t respect the first layer at all! Even if I specified a for it. So I dived back into the layer-list and began a painful process of developing a Samsung-proof solution.

This is what I ended up with:

And it was actually almost correct… almost, because another device (another Samsung… I wonder if that was just a coincidence or not) had a different issue with it:

Some devices seem to be displaying black if there is no tag specified within it.

A small change fixes the issue (this time a copyable version):

And to generalize this whole idea a bit:

If you want to see some of layer-lists that I tried (especially those that weren’t working correctly on all devices) you can see my demo app here.

Источник

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