Add background image to android ListView using Picasso

I need to add a background image to a ListView. I would usually call listview.setBackground(myImage) . But the image comes from the server, so I need to use Picasso to load the image against the background of my ListView. How to do it?

+5
source share
1 answer

Option 1

Define an anonymous subclass of com.squareup.picasso.Target

 Picasso.with(yourContext) .load(yourImageUri) .into(new Target() { @Override @TargetApi(16) public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { yourListView.setBackgroundDrawable(new BitmapDrawable(bitmap)); } else { yourListView.setBackground(new BitmapDrawable(getResources(), bitmap)); } } @Override public void onBitmapFailed(Drawable errorDrawable) { // use error drawable if desired } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { // use placeholder drawable if desired } }); 

Second option

Subclass ListView and implement com.squareup.picasso.Target

 public class PicassoListView extends ListView implements Target { public PicassoListView(Context context, AttributeSet attrs) { super(context, attrs); } public PicassoListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override @TargetApi(16) public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { setBackgroundDrawable(new BitmapDrawable(bitmap)); } else { setBackground(new BitmapDrawable(getResources(), bitmap)); } } @Override public void onBitmapFailed(Drawable errorDrawable) { // use error drawable if desired } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { // use placeholder drawable if desired } } 

What can you do:

 Picasso.with(yourContext) .load(yourImageUri) .into(yourListView); 
+11
source

Source: https://habr.com/ru/post/1204070/


All Articles