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

Android Studio烹饪App项目:Drawable图片导入路径问题

问题解决:Android中从Drawable资源加载图片到Recette类

你的代码核心问题是错误使用了Drawable.createFromPath()方法——这个方法用于加载设备文件系统(如SD卡)中的图片路径,而非应用内置的drawable资源。要加载drawable文件夹内的图片,必须通过Android资源系统实现,具体方案如下:

修正步骤

  1. 传入Context对象:获取应用资源必须依赖Context,需在Recette的构造方法中添加该参数。
  2. 转换资源名称为ID:通过getResources().getIdentifier()将图片文件名转换成对应的资源ID。
  3. 加载Drawable对象:使用getDrawable()(API 21及以上)或兼容方法获取Drawable实例。

修正后的代码

package com.example.projet_info0306;

import android.content.Context;
import android.graphics.drawable.Drawable;

public class Recette {
    private String nom;
    private Etape[] steps;
    private Drawable demo; // 遵循Java小驼峰命名规范

    // 构造方法添加Context参数,移除多余逗号
    public Recette(Context context, String n, Etape[] e, String imgName) {
        nom = n;
        steps = e;
        // 根据图片名称获取drawable资源ID
        int drawableId = context.getResources().getIdentifier(imgName, "drawable", context.getPackageName());
        // 加载Drawable并做容错处理
        if (drawableId != 0) {
            demo = context.getDrawable(drawableId);
        } else {
            // 资源不存在时设置默认图(需提前在drawable中添加default_img资源)
            demo = context.getDrawable(R.drawable.default_img);
        }
    }
}

使用说明

  • 调用构造方法时需传入Context实例(如Activity或Application Context),示例:new Recette(this, "番茄炒蛋", stepsArray, "tomato_egg")
  • imgName只需传入图片文件名(不带.png后缀和@drawable/前缀),例如图片文件是tomato_egg.png,则传"tomato_egg"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:45:37