是否可以将图像添加为 class 属性?

Is it possible to add an image as a class attribute?

我正在创建一个 class 来盛放不同的菜肴,它的属性是标题、难度、类型和时间。但我还想要一个在创建 class 的 object 时显示的图像。如何将图像 .png 设置为 class?

的属性

代码如下:

public class Dish {

    private String name;
    private String time;
    private String type;
    private Whatevergoesinhere image;
    private int difficulty;


    public Dish(String name, String time, String type, Whatevergoesinhere image, int difficulty) {
        this.name = name;
        this.time = time;
        this.type = type;
        this.image = image;
        this.difficulty= difficulty;
    }

    public String getName() {
        return name;
    }

    public String getTime() {
        return time;
    }

    public String getType() {
        return type;
    }

    public Whatevergoesinhere getImage() {
        return image;
    }

    public int getDifficulty() {
        return difficulty;
    }

    public static final Dish[] dishes = {
            new Dish("Judías verdes con patatas", "45 min.", "verduras", "R.id.ic_launcher_background.xml", )
    }
}

我试过使用 BufferedImage,但 Android 不支持它。

请大家帮忙,有什么想法就说吧。

继续我的评论:"If you get these images from application resources (res folder) then you can just pass drawable ID that will be later used to set image resource on an ImageView."

为此,您需要将 image 变量声明更改为:

import android.support.annotation.DrawableRes
// import androidx.annotation.DrawableRes: Use this import if you are using AndroidX dependencies

public class Dish {

    ...
    @DrawableRes
    private int image;
    ...

然后您还需要将构造函数和 getter 方法声明更改为这种形式:

    public Dish(..., @DrawableRes int image, ...) {
        ...
        this.image = image;
        ...
    }

    ...

    @DrawableRes
    public int getImage() {
        return image;
    }

稍后当使用此数据保存 class 时,您可以简单地使用 ImageView.setImageResource 来显示您拥有的图像。