How To Load Layout Background Using Picasso
None of the solutions above worked for me. But @Thiha's solution was the closest. The below worked for me:
final ImageView img = new ImageView(this);
Picasso.with(img.getContext()).load(url).into(img, new com.squareup.picasso.Callback() {
@Override
public void onSuccess() {
collapsingToolbarLayout.setBackgroundDrawable(img.getDrawable());
}
@Override
public void onError() {
}
});
I use an ImageView as temporary ImageHolder. At first, load image with picasso into ImageView and set Layout Background from this ImageView by using getDrawable.
ImageView img = new ImageView(this);
Picasso.with(this)
.load(imageUri)
.fit()
.centerCrop()
.into(img, new Callback() {
@Override
public void onSuccess() {
myLayout.setBackgroundDrawable(img.getDrawable());
}
@Override
public void onError() {
}
});
You can use Picasso's Target:
Picasso.with(this).load("http://imageUrl").into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
mYourLayout.setBackground(new BitmapDrawable(bitmap));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
UPDATE
As @BladeCoder mentioned in the comment, Picasso holds a weak reference to Target objects, hence it is likely to be garbage collected.
So, following Jake Wharton's comment on one of the issues, i think this could be a good way to go:
CustomLayout mCustomLayout = (CustomLayout)findViewById(R.id.custom_layout)
Picasso.with(this).load("http://imageUrl").into(mCustomLayout);
CustomLayout.java:
public class CustomLayout extends LinearLayout implements Target {
public CustomLayout(Context context) {
super(context);
}
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
setBackground(new BitmapDrawable(getResources(), bitmap));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
//Set your error drawable
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
//Set your placeholder
}
}