我正在创建一个容纳不同菜肴的类,其属性是标题,难度,类型和时间。但是我还希望在创建该类的对象时将显示一个图像。如何设置图像.png作为类的属性?
这里是代码:
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不支持。
[请帮助,如果您有任何想法请告诉。
从我的评论继续:“如果您从应用程序资源(res
文件夹中获得这些图像,则可以传递可绘制的ID,以后将其用于在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; }
稍后使用此数据保存类时,您只需使用ImageView.setImageResource即可显示您拥有的图像。