I'm trying to load an image into a layer-list programatically. I found some solutions but somehow it does not work. Here is what I did:
layer_list.xml: (Set as background of RelativeLayout)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/red" />
<item
android:id="@+id/replace"
android:drawable="@drawable/placeholder" />
<item
android:bottom="-250dp"
android:left="0dp"
android:right="-250dp"
android:top="250dp">
<rotate
android:fromDegrees="-10"
android:pivotX="0%"
android:pivotY="100%">
<shape android:shape="rectangle">
<solid android:color="@color/white" />
</shape>
</rotate>
</item>
</layer-list>
Code to load bitmap into layer-list:
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
LayerDrawable layerDrawable = (LayerDrawable) ResourcesCompat.getDrawable(getResources(), R.drawable.layer_list, null);
layerDrawable.setDrawableByLayerId(R.id.replace, drawable);
But somehow the placeholder image is never replaced with the new bitmap. What am I doing wrong here?
EDIT: This is how I load the image:
private void loadImageIntoLayerList(Context context, String url) {
// To get image using Fresco
ImageRequest imageRequest = ImageRequestBuilder
.newBuilderWithSource(Uri.parse(url))
.setProgressiveRenderingEnabled(true)
.build();
ImagePipeline imagePipeline = Fresco.getImagePipeline();
DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline
.fetchDecodedImage(imageRequest, context);
BaseBitmapDataSubscriber dataSubscriber = new BaseBitmapDataSubscriber() {
@Override
public void onNewResultImpl(@Nullable Bitmap bitmap) {
// You can use the bitmap in only limited ways
// No need to do any cleanup.
if (bitmap != null) {
Drawable drawable = new BitmapDrawable(getResources(), bmp);
LayerDrawable layerDrawable = (LayerDrawable) ResourcesCompat.getDrawable
(getResources(), R.drawable.layer_list, null);
if (layerDrawable != null) {
layerDrawable.setDrawableByLayerId(R.id.cover_image, drawable);
header.setBackground(layerDrawable);
}
}
}
@Override
public void onFailureImpl(DataSource dataSource) {
// No cleanup required here.
}
};
dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance());