I'm creating a class that will hold different dishes, and its properties are the title, the difficulty, the type and the time. But I also want an Image that will be displayed when an object of that class is created. How can I set an image, .png as an attribute of a class?
Here's the code:
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", )
}
}
I've tried using BufferedImage, but it's not supported in Android.
Please help, if you have any idea just tell.
Continuing from my commentary: "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
."
In order to do that you need to change image
variable declaration to this:
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;
...
And then you also need to change constructor and getter method declarations to this form:
public Dish(..., @DrawableRes int image, ...) {
...
this.image = image;
...
}
...
@DrawableRes
public int getImage() {
return image;
}
Later when this data holding class is used you can simply use ImageView.setImageResource to display an image you have.