异常:ex:android.content.res.Resources$NotFoundException:Drawable com.my.app:drawable/draghandlerounded,资源 ID #0x7f0801b5

问题描述 投票:0回答:1

有时,对于我项目中的一些可绘制对象,我会遇到异常:

Exception: ex:android.content.res.Resources$NotFoundException: Drawable com.my.app:drawable/draghandlerounded with resource ID #0x7f0801b5

我的项目(2000)中有一个可绘制对象列表。然后我收到了可绘制的名称,转换得到可绘制的ID:


val iconDrawableId = resourceProvider.getAppContext().resources.getIdentifier(iconName, "drawable", resourceProvider.getAppContext().packageName

我在

ContextCompat
类中变得可绘制

ContextCompat.getDrawable(resourceProvider.getAppContext(), iconDrawableId)

draghandlerounded.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="32px"
    android:height="32px"
    android:viewportWidth="24"
    android:viewportHeight="24">
  <path
      android:pathData="M19,9H5c-0.55,0 -1,0.45 -1,1s0.45,1 1,1h14c0.55,0 1,-0.45 1,-1s-0.45,-1 -1,-1zM5,15h14c0.55,0 1,-0.45 1,-1s-0.45,-1 -1,-1H5c-0.55,0 -1,0.45 -1,1s0.45,1 1,1z"
      android:fillColor="#000000"
      android:fillAlpha="0.87"/>
</vector>


我尝试使用主题绘制,但没有帮助。

android drawable
1个回答
0
投票

确保可绘制名称有效且存在于资源目录中。

fun getDrawable(context: Context, iconName: String): Drawable? {
    val resourceId = context.resources.getIdentifier(iconName, "drawable", context.packageName)
    return if (resourceId != 0) {
        try {
            ContextCompat.getDrawable(context, resourceId)
        } catch (e: Resources.NotFoundException) {
            Log.e("DrawableError", "Drawable not found: $iconName", e)
            null
        }
    } else {
        Log.e("DrawableError", "Invalid drawable name: $iconName")
        null
    }
}

如何使用:

val iconDrawable = getDrawable(resourceProvider.getAppContext(), iconName)
if (iconDrawable != null) {
    // Use the drawable
} else {
    // Handle the missing drawable
}

使用这种方式可以避免崩溃,并可以检查哪个图像有问题并稍后修复路径。

© www.soinside.com 2019 - 2024. All rights reserved.