Can I load a picture with Picasso to the action ba

2019-02-08 13:41发布

问题:

I've been using Picasso extensively to retrieve images over the internet to my app. Now, I've run into a situation where I need to retrieve a small image to the action bar (like a logo next to the title text).

Is it possible to do this with Picasso? If so, how would I do that?

回答1:

I found out a solution which uses Picasso's Target class and does not require a custom Action Bar.

final ActionBar ab = getSupportActionBar();
Picasso.with(this)
       .load(imageURL)
       .into(new Target()
       {
           @Override
           public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
           {
               Drawable d = new BitmapDrawable(getResources(), bitmap);
               ab.setIcon(d);
               ab.setDisplayShowHomeEnabled(true);
               ab.setDisplayHomeAsUpEnabled(true);
           }

           @Override
           public void onBitmapFailed(Drawable errorDrawable)
           {
           }

           @Override
           public void onPrepareLoad(Drawable placeHolderDrawable)
           {
           }
       });


回答2:

You load the picture like you would any other Picasso image, but one extra step is to add a custom action bar. Something like:

    final View actionBarLayout = getLayoutInflater().inflate(R.layout.custom_action_bar, null);

    actionBar = getSupportActionBar();
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(false);
    actionBar.setCustomView(actionBarLayout);

and then

 myIcon = (ImageView) actionBarLayout.findViewById(R.id.myIcon);
 Picasso.with(this).load("http://myimage.png").into(myIcon);