2013-07-04 27 views
1

你好我試圖以編程方式將圖像添加到一個活動的Android應用程序中的活動如何將圖像編程方式添加到Android

我有這樣的:

for (int i = 0; i < num_devices; i++) { 

     ImageView imageView = new ImageView(this); 
     LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams 
      (ViewGroup.LayoutParams.WRAP_CONTENT, 
      ViewGroup.LayoutParams.WRAP_CONTENT); 
     imageView.setLayoutParams(vp); 

     try { 
      Class res = R.drawable.class; 
      Field field = res.getField(device_types.get(i)); 
      int resId = field.getInt(null); 
      imageView = (ImageView) findViewById(resId); 
     } 
     catch (Exception e) { 
      Log.e("MyTag", "Failure to get drawable id.", e); 
     } 

     LinearLayout link_devices = (LinearLayout) findViewById(R.id.link_devices); 
     link_devices.addView(imageView); 

但是它沒有讓我圖像的位置(我嘗試和共達,getLeft等得到0 ..)

我做錯了,是爲做

回答

0

您沒有設置IMA的正確方法ge在該imageview上,並且已將WRAP_CONTENT設置爲佈局參數,這意味着imageView的大小與您在其上設置的圖像的大小相同。 由於沒有圖像被附加的ImageView的大小爲0。

嘗試設置的圖像,使用所述碼中的任何一個; - imageView.setImageBitmap(位圖BM),setImageDrawable(可繪製可繪製的)或setImageResource(INT渣油)。

我不明白你這個代碼做什麼&它不是必需的:

Class res = R.drawable.class; 
Field field = res.getField(device_types.get(i)); 
int resId = field.getInt(null); 
imageView = (ImageView) findViewById(resId); 
+0

代碼基本上可以讓我對我的字符串的情況下轉換成渣油形象,所以我基本上使用setImageResource - >你能解釋一下你認爲需要切出什麼代碼 – cxzp

+0

最簡單的是setImageResource(int ResId)。 如果您在名爲x.png的res/drawable文件夾中有圖像,您可以通過設置圖像 「imageView.setImageResource(R.drawable.x);」 – vakman

+0

我將代碼更改爲http://fixee.org/paste/lg2zs9o/,但Syst.out.prinltlns仍然給我0 – cxzp

相關問題