[英]How to set ImageView Resource from Java Image data type in Android
I am trying to set a Image View resource from a Image Data Type我正在尝试从图像数据类型设置图像视图资源
Something like就像是
//this line is not working
Image storeImage = new Image(R.drawable.butterfly);
ImageView mainImage = findViewById(R.id.mainImage);
//this line is not working either
mainImage.setImageResource(storeImage);
For my work对于我的工作
I need to store image in a variable then use it later for Image view我需要将图像存储在变量中,然后稍后将其用于图像视图
Set the drawable directly, to the view:直接将drawable设置为视图:
//store the id of the drawable
int image = R.drawable.butterfly
ImageView mainImage = findViewById(R.id.mainImage);
mainImage.setImageResource(image);
In general, your image is stored, once you added it to your Drawable resource folder.通常,一旦您将图像添加到 Drawable 资源文件夹,就会存储您的图像。 You can access it with an ID which can be stored in a variable (datatype int):
您可以使用可以存储在变量(数据类型 int)中的 ID 访问它:
int storeImage = R.drawable.butterfly;
Then you have to make your ImageView accessible as you already did:然后你必须让你的 ImageView 像你已经做的那样可以访问:
ImageView mainImage = findViewById(R.id.mainImage);
Your code mainImage.setImageResource(storeImage);
您的代码
mainImage.setImageResource(storeImage);
doesn't work because "storeImage" is an int, but the function expects a Drawable.不起作用,因为“storeImage”是一个 int,但 function 需要一个 Drawable。 Each time you want to convert the ID into a Drawable, you have to use
getDrawable(storeImage);
每次要将ID转换为Drawable,都得使用
getDrawable(storeImage);
. .
Therefore your whole code would look like this:因此,您的整个代码将如下所示:
int storeImage = R.drawable.butterfly;
ImageView mainImage = findViewById(R.id.mainImage);
mainImage.setImageDrawable(getDrawable(storeImage));
mainImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.butterfly)); mainImage.setImageDrawable(ContextCompat.getDrawable(这个,R.drawable.butterfly));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.