In Mobikul application, we allow user to provide different category icon’s for each category. Category icons can be changed at any instance of time.
In this blog we will see how the icons of any menu item can be changed.
Let us explore it step by steps:
1. Using Picasso Library
A powerful image downloading and caching library for Android.
compile ‘com.squareup.picasso:picasso:2.5.2’
2. Using Target Interface of Picasso Library
Target Interface represents an arbitrary listener for image loading. This interface is generally used as a mediator between our view and source image.
There are three methods that are overridden when we use this inteface.
A. void onBitmapLoaded(Bitmap bitmap, LoadedFrom from)
Callback when an image has been successfully loaded.
B. void onBitmapFailed(Drawable errorDrawable)
Callback indicating the image could not be successfully loaded.
C. void onPrepareLoad(Drawable placeHolderDrawable)
Callback invoked right before your request is submitted.
3. Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
final Target mTarget = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) { Log.d("DEBUG", "onBitmapLoaded"); BitmapDrawable mBitmapDrawable = new BitmapDrawable(getResources(), bitmap); // mBitmapDrawable.setBounds(0,0,24,24); // setting icon of Menu Item or Navigation View's Menu Item navigationMenuItem.setIcon(mBitmapDrawable); } @Override public void onBitmapFailed(Drawable drawable) { Log.d("DEBUG", "onBitmapFailed"); } @Override public void onPrepareLoad(Drawable drawable) { Log.d("DEBUG", "onPrepareLoad"); } }; Picasso.with(this).load(tempUrl).into(mTarget); |
In this sample code, we have create a new instance of Interface Target and passed this instance to picasso library for image loading. When the drawable is loaded onBitmapLoaded method is called and provide bitmap of the image.
Since bitmap cannot be directly added to a menu item. So, we have converted this bitmap to bitmap drawable. And then we can use this drawable (Bitmap Drawable) as a icon in Menu item.
Further Reading: