Héctor
Héctor

Reputation: 26054

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?

Upvotes: 7

Views: 4701

Answers (3)

Yuichi Akiyoshi
Yuichi Akiyoshi

Reputation: 419

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");
  }      
})

Upvotes: 1

Ege Kuzubasioglu
Ege Kuzubasioglu

Reputation: 6282

 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");
  }      
}

Upvotes: 1

Nouman Ch
Nouman Ch

Reputation: 4121

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.

Upvotes: 3

Related Questions