android-jetpack-composeandroid-jetpack-compose-ui

Get an app icon and display in Jetpack Compose


Trying to load icons for applications on the phone, I use the following code:

val drawable = packageManager.getApplicationIcon(app.packageName)
Icon(
    drawable.toBitmap(config = Bitmap.Config.ARGB_8888).asImageBitmap()
    , contentDescription = "Icon", modifier = Modifier
        .padding(8.dp),
    tint = MaterialTheme.colorScheme.secondary
)

This gives a round filled circle and no icon for most apps. why?


Solution

  • Ok, turns out you shouldn’t pass a bitmap to an icon and expect all colors to be preserved.

    The icon you receive from an app is a bitmap with possibly many colors, so you will need an Image or drawImage (inside Canvas) to draw it. Changing the above code to the following will fix the issue.

    val drawable = packageManager.getApplicationIcon(app.packageName)
    Image(
        drawable.toBitmap(config = Bitmap.Config.ARGB_8888).asImageBitmap()
        , contentDescription = "Image", modifier = Modifier
            .size(100.dp) //Optional, but keeps the image reasonably small
            .padding(8.dp)
    
    )