Question

I have the following LayerDrawable:

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

    <item
        android:id="@+id/image_source"
        android:bottom="6dp"
        android:drawable="@drawable/default"
        android:left="14dp"
        android:right="14dp"
        android:top="6dp">
    </item>
    <item android:drawable="@drawable/metaphor_photo_portrait"/>

</layer-list>

I need to be able to dynamically sustitute the image in @+id/image_source from the code. I succeeed to do on Honeycomb+ devices using:

mLayerDrawable.setDrawableByLayerId(R.id.image_source, drawable);
mLayerDrawable.invalidateSelf();

However, this does not work on Gingerbread devices as setDrawableByLayerId is unstable for Gingerbread devices (link 1, link 2). I am advised to construct the LayerDrawable from scratch. I started doing that and am currently faced with the problem of setting the intristicInset of the first layer.

I tried using

mLayerDrawable.setLayerInset(0, dp14, dp6, dp14, dp6);

Where dpxx are constants I calculate myself. However it seems this method is not working on Gingerbread either (link 1).

Thus I decided to try to do it the other way - set the bounds of the restangle of the drawable I set on the first layer:

drawable.setBounds(dp14, dp6, dp90 - dp14, dp90 - dp6);

Perfect, however it seems that bounds settings on LayerDrawable layer are ignored (link 1)

Now I am advised to use combination of two image viwes. However my LayerDrawable is part of LevelListDrawable and I think that I can not include layout in such.

All in all this leave me not being able to modify the contents of my LayerDrawable in any way on pre-Honeycomb devices. Any advises on how should I proceed are appreciated!

Was it helpful?

Solution

drawable.setBounds(mLayerDrawable.findDrawableByLayerId(R.id.image_source).getBounds());
mLayerDrawable.setDrawableByLayerId(R.id.image_source, drawable);        
mLayerDrawable.invalidateSelf();

reference: https://github.com/ytRino/LayerDrawableSample/blob/master/src/net/nessness/android/sample/layerdrawable/LayerDrawableSampleActivity.java

OTHER TIPS

Finally we got it to wok in some very weird way:

LayerDrawable layerDrawable = (LayerDrawable) getResources().getDrawable(layerDrawableResourceId);
layerDrawable.setDrawableByLayerId(R.id.image_source, drawable);
Drawable[] layers = {
   layerDrawable };
LayerDrawable layerDrawableNew = new LayerDrawable(layers);

A colleague of mine found that if we create new LayerDrawable, set the not-working method to it and then wrap this LayerDrawable in yet another, the visualization is correct (both the image is changed and the paddings preserved). Quite a tweaking around and a lot of "Don't touch this it's magic", but this is the best solution we could work out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top