我试图从一个图像数据类型中设置一个图像视图资源。
类似
//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);
对于我的工作
我需要将图像存储在一个变量中,然后在图像视图中使用。
直接把drawable,设置到视图中。
//store the id of the drawable
int image = R.drawable.butterfly
ImageView mainImage = findViewById(R.id.mainImage);
mainImage.setImageResource(image);
一般情况下,你的图像被存储,一旦你把它添加到你的Drawable资源文件夹中,你就可以用一个ID来访问它,这个ID可以存储在一个变量中(数据类型为int)。
int storeImage = R.drawable.butterfly;
然后你必须让你的ImageView像你已经做的那样被访问。
ImageView mainImage = findViewById(R.id.mainImage);
你的代码 mainImage.setImageResource(storeImage);
不起作用,因为 "storeImage "是一个int,但函数期望的是一个Drawable。每次你想把ID转换为Drawable时,你必须使用 getDrawable(storeImage);
.
因此,你的整个代码会是这样的。
int storeImage = R.drawable.butterfly;
ImageView mainImage = findViewById(R.id.mainImage);
mainImage.setImageDrawable(getDrawable(storeImage));
mainImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.butterfly))。