Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Load Layout Background Using Picasso

Can anyone point me towards an example of how one might change an XML layout's background programatically using Picasso? All the examples I've found are able to update an ImageView using Picasso - but not a layout background.

Unable to set LinearLayout BackgroundResource from URL using Picasso

like image 682
AndroidAndroidAndroid Avatar asked Jul 16 '15 21:07

AndroidAndroidAndroid


People also ask

How do you load an image into an imageView from an image URL using Picasso?

Image loading using Picasso is very easy, you can do it like this way Picasso. get(). load("http://i.imgur.com/DvpvklR.png").into(imageView); and in their website you can get every details. In your case you can parse every image URL and use RecyclerView to show them along with Picasso.

What is Picasso library in Android?

Picasso allows for hassle-free image loading in your application—often in one line of code! Picasso. get(). load("https://i.imgur.com/DvpvklR.png").into(imageView);


1 Answers

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
    }
}
like image 137
mmark Avatar answered Sep 28 '22 04:09

mmark