2014-12-04 51 views
1

指定SRC我想显示的图像,根据的int imgch显示的图像,而不在XML

这是我的onCreate值:

ImageView image = (ImageView)findViewById(R.id.gimage); 
    Resources res = getResources(); 
    Drawable gameImage = res.getDrawable(images[imgch]); 

在我的XML和这样的:

 <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/gimage" /> 

如何让它在活动中显示正确的图像?

+0

你可以使用Java代码设置图像 - setImageResource或Drawable。 – Eenvincible 2014-12-04 19:02:06

+0

我用Drawable右键?我该怎么处理它? – 2014-12-04 19:03:22

回答

1

检查ImageView#setImageDrawable。所以,你应该有image.setImageDrawable(gameImage)

2

是的,但与Java端代码

ImageView img = (ImageView) findViewById(R.id.gimage); 
img.setImageDrawable(getDrawable(R.drawable.my_image_name)); 

如果你从远程URL想负载你可能会使用这个

https://github.com/nostra13/Android-Universal-Image-Loader

+0

但我不能给这个名字,因为它取决于imgch的值。有没有办法解决这个问题? – 2014-12-04 19:10:59

+0

请看下面的答案,我将答案作为独立答案添加回答 – BredeBS 2014-12-04 19:19:04

0

使用

Resources resources = getResources(); 
image.setImageDrawable(resources.getDrawable(R.drawable.myfirstimage)); 
+0

请详细说明**为什么**通过编辑答案来回答问题。 – 2014-12-04 19:48:26

0

创建数组

int[] images; 

protected void onCreate(Bundle savedInstanceState) { 

添加此

images = new int[3]; 
images[0] = R.drawable.first_image; 
images[1] = R.drawable.second_image; 
images[2] = R.drawable.third_image; 

,然后你的代码(其中imgch为整数)

... 
Drawable gameImage = res.getDrawable(images[imgch]); 
... 
+0

这就是我已经拥有的,现在XML应该是什么样子? – 2014-12-04 19:23:56

+0

这个XML是正确的...你在控制台日志中有任何错误吗? – BredeBS 2014-12-04 19:30:13

+0

不,但它没有显示任何内容,imageview在线性布局中占用零空间 – 2014-12-04 19:32:49