I wanted to set a custom drawable to be the android:src of FloatingActionButton in this layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:sscce="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
sscce:fabSize="normal"
android:src="@drawable/fab_drawable" />
</LinearLayout>
I was expecting something like:
But I got:
Here is the custom layer-list drawable, which contains a few shape drawables:
res/drawable/fab_drawable.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="oval">
<solid android:color="#1AFF00" /> <!-- green -->
<size android:width="150dp"
android:height="150dp"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#FC00FF" /> <!-- pink -->
<size android:width="100dp"
android:height="100dp"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#0040FF" /> <!-- blue -->
<size android:width="40dp"
android:height="40dp" />
</shape>
</item>
<item>
<shape android:shape="oval" >
<stroke android:width="3dp"
android:color="#FF0000"/> <!-- red -->
<solid android:color="#FFBF00" /> <!-- yellow -->
<size android:width="24dp"
android:height="24dp" />
</shape>
</item>
</layer-list>
Although it is syntactically possible to use
dp
values, this seems to cause problems with some density categories, so better usepx
instead. Shape drawables will be scaled to fit their containingView
anyway, the values you provide just have an influence on the proportions of the shape.For your layer-list drawable, you have to provide a common "frame" for the size of all the shape drawables as each layer will be scaled to fit the
View
independently of the others.This means that the smaller circles need some additional information about how far from the edge they should be drawn. For a circle centered in its container:
distance = (container_size - circle_size) / 2
If we take
150px
as the basic size for all the drawables, then for example the pink circle (size100px
) needs25px
distance to the edges of its container.You can provide this information by setting attributes to each
item
:Note that it's important to have attributes not only for top/ left but also for bottom/ right. If you leave out any attributes then the drawable will be scaled to touch the respective edge, so the circle shape could be rendered as an oval or as an off-center circle.