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?
To add actions to the action bar, create a new XML file in your project's res/menu/ directory. The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar.
For using Picasso in the android project, we have to add a dependency in the app-level gradle file. So, For adding dependency open app/build. gradle file in the app folder in your Android project and add the following lines inside it.
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)
{
}
});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With