android, background, layer-list and scalable bitmap item

Lukasz 'Severiaan' Grela picture Lukasz 'Severiaan' Grela · Sep 1, 2011 · Viewed 33.5k times · Source

I have the following drawable set as a background:

<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">

<item>
  <bitmap android:src="@drawable/base_bg"
    android:gravity="bottom" />
</item>
<item android:top="10dp" android:left="10dp">
  <bitmap android:src="@drawable/decoration1"
    android:gravity="top|right" 
    android:width="25dp" 
    android:height="25dp"  />
</item>
<item android:top="10dp" android:left="10dp">
  <bitmap android:src="@drawable/decoration2"
    android:gravity="top|right" 
    android:width="25dp" 
    android:height="25dp" 
    />
</item>
</layer-list>

It displays all the bitmaps (base_bg, decoration1, and decoration2) but I can't find a way to modify the size of them. I would like to have the main background and on top of it the decorations that will have different sizes based on the dpi. Is there a simple way to do that, or do I actually have to have a bunch of "decorations" for different dpi's? It isn't good and I would like to have the scale/resize option instead!

The android:width and android:height attributes are something that I would like to find, but I know that it doesn't work. At the moment I am using different versions for different DPI but hoped it could be a bit more user friendly.

Answer

David Jesse picture David Jesse · Sep 13, 2011

I don't know how are these images, but, for example, you could make a big image and use it in a item android:drawable field, in this way the image takes the item's size.

<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">

<item>
  <bitmap android:src="@drawable/base_bg"
    android:gravity="bottom" />
</item>
<item android:top="10dp" android:left="10dp" android:drawable="@drawable/decoration1">
</item>
<item android:top="10dp" android:left="10dp" android:drawable="@drawable/decoration2">
</item>
</layer-list>

Other solutions could be to do it programmatically with LayerDrawable (here) and Drawable (here) classes. You could construct the Layer Object with 3 Drawable Objects and then choose the correct size on each Drawable object with the method setBounds(Rect ).

I hope it helps you.