[英]How to display installed app icon in jetpack compose
In jetpack compose, you can display drawables easily with the Image composable like this:在 Jetpack Compose 中,您可以使用 Image 可组合项轻松显示可绘制对象,如下所示:
Image(painter = painterResource(id = R.drawable.my_drawable))
I'm building an app that requires listing all the apps on the device and I need to display their icons.我正在构建一个需要列出设备上所有应用程序的应用程序,并且我需要显示它们的图标。 I managed to get the icons using the
PackageManager
class:我设法使用
PackageManager
class 获取图标:
val packageManager = context.packageManager
val installedPackages = packageManager.getInstalledPackages(0)
val packageInfo = installedPackages[0]
val iconId: Int = packageInfo.applicationInfo.icon
Then:然后:
Image(painter = painterResource(id = iconId))
But the app crashes everytime.但是应用程序每次都会崩溃。 I don't know where the problem is?
不知道问题出在哪里? Any Idea?
任何的想法? Thanks
谢谢
android.content.res.Resources$NotFoundException: Resource ID #0x7f030001
For some reason icon
may contain identifier that points to non-existent drawable.由于某种原因,
icon
可能包含指向不存在的可绘制对象的标识符。
To get application icon use method loadIcon
:要获取应用程序图标,请使用方法
loadIcon
:
val icon: Drawable = applicationInfo.loadIcon(packageManager)
Or method getApplicationIcon
from PackageManager:或者来自 PackageManager 的方法
getApplicationIcon
:
val icon: Drawable = packageManager.getApplicationIcon(applicationInfo)
Then, use AndroidDrawablePainter to convert Drawable to Painter:然后,使用AndroidDrawablePainter将 Drawable 转换为 Painter:
Image(painter = AndroidDrawablePainter(icon))
Or DrawablePainter is available in accompanist library:或者DrawablePainter在伴奏库中可用:
Image(painter = DrawablePainter(icon))
If you're using the Coil library , rememberImagePainter
will accept an Any?
如果您使用的是Coil 库,
rememberImagePainter
会接受Any?
as its data
argument, allowing you to use the Drawable
returned from the PackageManager
, like so:作为其
data
参数,允许您使用从PackageManager
返回的Drawable
,如下所示:
Image(
painter = rememberImagePainter(
data = LocalContext.current.packageManager.getApplicationIcon("com.package.example")
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.