2014-12-04 28 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