Skip to content Skip to sidebar Skip to footer

Setting Menuitem Icon From Url - Android

I want to set a MenuItem in my ActionBar which leads to the user profile page in my app. I would like the icon for that to be his profile picture for which I have the URL and can c

Solution 1:

You could do something like this to set the icon from a bitmap:

myMenuItem.setIcon(newBitmapDrawable(getResources(), myBitmap));

In your code this would looks a bit like this:

publicbooleanonCreateOptionsMenu( Menu menu ) {
    MenuInflaterinflater= getMenuInflater();
    inflater.inflate( R.menu.actionbar, menu );
    userItem = menu.findItem(R.id.userItem);

    BitmapmyBitmap=//get your bitmap
    userItem.setIcon(newBitmapDrawable(getResources(), myBitmap));

    return menu;
}

You'll need to get the file from the URL and turn it into a Bitmap first. Note that this will be slow, since if you are doing this when your app is started, the user will have to wait until the file is downloaded before the app will be shown. If your icon changes infrequently, I'd recommend caching it on the device and reusing the locally stored copy.

Also check the "Changing the menus at runtime" section here.

Solution 2:

Kotlin - Picasso Solution

extension function

fun com.squareup.picasso.Target.picassoLoad(url: String, resources: Resources): com.squareup.picasso.Target {
    Picasso.get().load(url)
            .resize(resources.getDimension(R.dimen.menuIconSize).toInt(),
                    resources.getDimension(R.dimen.menuIconSize).toInt())
            .into(this)
    returnthis
}

in your activity (note that you need to keep a strong reference on target to work)

privatevar target : com.squareup.picasso.Target? = nulloverridefunonCreateOptionsMenu(menu: Menu): Boolean {
    menuInflater.inflate(R.menu.basemenu, menu)

    menu.findItem(R.id.menu_you_want)?.let { menuItem ->

        target = object : com.squareup.picasso.Target {
            overridefunonPrepareLoad(placeHolderDrawable: Drawable?) {
                menuItem.setIcon(R.drawable.fallback_image)
            }

            overridefunonBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) {
                menuItem.setIcon(R.drawable.fallback_image)
            }

            overridefunonBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
                menuItem.icon = BitmapDrawable(resources, CircleTransform.getCroppedBitmap(bitmap!!))
            }

        }.picassoLoad(url, resources)
    }

    returnsuper.onCreateOptionsMenu(menu)
}

and circletransform class

classCircleTransform : Transformation {privatevar x: Int = 0privatevar y: Int = 0overridefuntransform(source: Bitmap): Bitmap {
        val size = Math.min(source.width, source.height)

        x = (source.width - size) / 2
        y = (source.height - size) / 2val squaredBitmap = Bitmap.createBitmap(source, x, y, size, size)
        if (squaredBitmap !== source) source.recycle()
        val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)

        val canvas = Canvas(bitmap)
        val paint = Paint()
        val shader = BitmapShader(squaredBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        paint.shader = shader
        paint.isAntiAlias = trueval r = size / 2f
        canvas.drawCircle(r, r, r, paint)

        squaredBitmap.recycle()
        return bitmap
    }


    overridefunkey() = "circle(x=$x,y=$y)"companionobject {
        fungetCroppedBitmap(bitmap: Bitmap): Bitmap {
            val output = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(output)

            val color = -0xbdbdbeval paint = Paint()
            val rect = Rect(0, 0, bitmap.width, bitmap.height)

            paint.isAntiAlias = true
            canvas.drawARGB(0, 0, 0, 0)
            paint.color = color
            canvas.drawCircle(bitmap.width / 2f, bitmap.height / 2f,
                    bitmap.width / 2f, paint)
            paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
            canvas.drawBitmap(bitmap, rect, rect, paint)
            return output
        }
    }
}

Solution 3:

I was searching for this as well and recently I found it from another stackoverflow answer which I'm giving reference link This one is for JAVA and I'm adding Kotlin code below.

Here is the code for kotlin code: imageUser is Url of image in string format. You should add it your own image url.

Glide.with(this).asBitmap().load(imageUser)
                    .into(object : SimpleTarget<Bitmap?>(150, 100) {
                        overridefunonResourceReady(
                            resource: Bitmap,
                            transition: Transition<inBitmap?>?
                        ) {
                            yourItemIcon.setIcon(BitmapDrawable(resources, resource))
                        }
                    })

Set your item as below inside the. onCreateOptionsMenu

overridefunonCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.menu_main, menu)
    val yourItemIcon  = menu!!.findItem(R.id.ic_topic_info)     
  returntrue

}

For new users: You should also add these lines of code to dependencies the build.gradle in app level for adding Glide library in your app.

implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'

Post a Comment for "Setting Menuitem Icon From Url - Android"