You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中如何引用资源路径?加载图片动画遇阻求助

Android中AssetManager加载图片路径错误的解决方法

核心问题

AssetManager仅用于访问assets目录下的文件,你当前尝试访问的res/drawable属于Android资源目录,二者是完全独立的资源体系,因此用assetManager访问res路径必然返回空列表。

解决方案一:将图片移至assets目录加载

步骤1:创建assets目录

在Android Studio中,右键点击app/src/main目录 → New → Folder → Assets Folder,按提示完成创建(默认路径为app/src/main/assets)。

步骤2:组织图片文件

在assets目录下创建子文件夹(例如anim_images),将需要加载的图片放入该子文件夹。

步骤3:正确调用loadPics函数

调用时传入assets下的子文件夹路径,例如:

val bitmapList = mutableListOf<Bitmap>()
loadPics(context, "anim_images", bitmapList)

修正你的loadPics函数(修复路径拼接与流关闭问题)

fun loadPics(context: Context, path: String, iconList: MutableList<Bitmap>): MutableList<Bitmap> {
    val assetManager = context.assets
    try {
        val files = assetManager.list(path) ?: return iconList // 处理空列表情况
        for (fileName in files) {
            assetManager.open("$path/$fileName").use { inputStream -> // use自动关闭流
                val bitmap = BitmapFactory.decodeStream(inputStream)
                iconList.add(bitmap)
            }
        }
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return iconList
}

解决方案二:直接加载drawable目录下的图片

如果不想移动图片,可通过资源ID直接加载drawable中的图片(适合命名有规律的图片,例如anim_0.png、anim_1.png...):

fun loadDrawableAnimPics(context: Context, iconList: MutableList<Bitmap>): MutableList<Bitmap> {
    val resources = context.resources
    val packageName = context.packageName
    var index = 0
    while (true) {
        // 根据图片命名规则获取资源ID
        val resId = resources.getIdentifier("anim_$index", "drawable", packageName)
        if (resId == 0) break // 无匹配资源时退出循环
        val bitmap = BitmapFactory.decodeResource(resources, resId)
        iconList.add(bitmap)
        index++
    }
    return iconList
}

注意事项

  • assets目录下的文件不区分密度,不会被Android系统优化,文件名严格区分大小写。
  • drawable目录下的图片会根据设备屏幕密度自动匹配对应drawable-xxhdpi等目录下的资源,无需手动指定路径。

内容的提问来源于stack exchange,提问作者duperele 11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 16:20:09