Create a LayerDrawable object programmatically
How can I create this drawable programmatically?
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<bitmap android:src="@drawable/android_red"
android:gravity="center" />
</item>
<item android:top="10dp" android:left="10dp">
<bitmap android:src="@drawable/android_green"
android:gravity="center" />
</item>
<item android:top="20dp" android:left="20dp">
<bitmap android:src="@drawable/android_blue"
and开发者_运维问答roid:gravity="center" />
</item>
</layer-list>
This wasn't too obvious until I read the comments under @OctavianDamiean's answer. His hyperlink is broken, but in order to programmatically set an item
's android:top
, android:bottom
, etc., reference LayerDrawable
's setLayerInset
method.
setLayerInset (int index, int l, int t, int r, int b)
int index
- the index of the Drawable
out of the Drawable
array (that you passed in as the LayerDrawable
's constructor parameter) that you want to modify.
int l, t, r, b
- Set these as you would in android:left
, android:top
, etc
It is pretty much completely described here. Just create a new instance of LayerDrawable
by passing its constructor an array of Drawable
objects.
精彩评论