Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load image from URI as layout background

I have used Picasso to load an image from my company's CDN into a ImageView:

ImageView imgView;
//...
Picasso.with(context).load(Uri.parse(url)).into(imgView);

But now I need load an image as a layout background:

RelativeLayout theLayout;
//...
Picasso.with(context).load(Uri.parse(url)).into(...);

Is it possible with Picasso? If not, should I use a ImageView instead of Relativelayout?

like image 927
Héctor Avatar asked Dec 26 '17 14:12

Héctor


3 Answers

you can use glide to download bitmap and set it as background from any layout.

Glide
        .with(getApplicationContext())
        .load("https://www.google.es/images/srpr/logo11w.png")
        .asBitmap()
        .into(new SimpleTarget<Bitmap>(100,100) {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
              Drawable dr = new BitmapDrawable(resource);
             theLayout.setBackgroundDrawable(dr);
                  // Possibly runOnUiThread()
            }
        });

but the better way is to use imageView on top of relativelayout and make it match_parent and show image on this imageview. this will help you directly use glide or picaso to load image in image view without memory errors.

like image 197
Nouman Ch Avatar answered Nov 10 '22 16:11

Nouman Ch


 Picasso.with(getActivity()).load(your url).into(new Target(){

  @Override
  public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
     yourlayout.setBackground(new BitmapDrawable(context.getResources(), bitmap));
  }

edit:

you may need to override following methods as well

@Override
  public void onBitmapFailed(final Drawable errorDrawable) {
      Log.e("TAG", "Failed");
  }

  @Override
  public void onPrepareLoad(final Drawable placeHolderDrawable) {
      Log.e("TAG", "Prepare Load");
  }      
}
like image 39
Ege Kuzubasioglu Avatar answered Nov 10 '22 18:11

Ege Kuzubasioglu


Yes. You can use Picasso for this. Please check following code :

Picasso.with(getActivity()).load(Uri.parse(url)).into(new Target(){

  @Override
  public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
     relativeLayout.setBackground(new BitmapDrawable(context.getResources(), bitmap));
  }

  @Override
  public void onBitmapFailed(final Drawable errorDrawable) {
      Log.d("TAG", "FAILED");
  }

  @Override
  public void onPrepareLoad(final Drawable placeHolderDrawable) {
      Log.d("TAG", "Prepare Load");
  }      
})
like image 1
Yuichi Akiyoshi Avatar answered Nov 10 '22 16:11

Yuichi Akiyoshi