2012-11-22 58 views
11

我想在圖像視圖中顯示圖像,所以我創建了一個文件夾 - drawableres並將圖像放在那裏。像apple.png。然後,我用這個代碼:如何在android中設置imageview中的圖像?

ImageView iv= (ImageView)findViewById(R.id.img_selected_image); 
String path = getApplication().getFilesDir().getAbsolutePath(); 
InputStream is = new FileInputStream(path + "/apple.png"); 
Drawable icon = new BitmapDrawable(is); 
Log.i("Fnord", "width="+icon.getIntrinsicWidth()+ 
    " height="+icon.getIntrinsicHeight()); 
iv.setImageDrawable(icon); 

但是當我運行它,它說,沒有在data/data/package-name/filesapple.png名稱的任何圖像。我想我把我的形象放在不合適的地方。我應該把我的形象放在哪裏?

+0

你還需要確保你的圖像不會被延伸https://themillibit.wordpress.com/2017/09/25/why-are-my-bitmaps-all-stretched/ –

回答

51

您可以直接在您的setimage中給出圖像名稱iv.setImageResource(R.drawable.apple);應該是。

+0

你的意思是我應該只寫:ImageView iv =(ImageView)findViewById(R.id.img_selected_image); iv.setImageResource(R.drawable.apple);另一個代碼不需要? – shadi

+0

是的,其他代碼不是必需的,但是請在'res> drawable'中添加你的圖像,然後在項目上執行一個'Clean',這樣它就會在你的'R.java'文件中自動生成以供引用。 – Anuj

+0

我應該手動製作一個可繪製文件夾嗎? – shadi

2

您投入res/drawable的圖像由Android處理。你沒有必要按照你的方式來獲取圖像。 你的情況,你可以簡單地調用iv.setImageRessource(R.drawable.apple)

只得到圖像(而不是將其添加到直接ImageView的),你可以調用Context.getRessources().getDrawable(R.drawable.apple)來獲得圖像

7

使用下面的代碼,

iv.setImageResource(getResources().getIdentifier("apple", "drawable", getPackageName())); 
1
 ImageView iv= (ImageView)findViewById(R.id.img_selected_image); 
     public static int getDrawable(Context context, String name)//method to get id 
     { 
     Assert.assertNotNull(context); 
     Assert.assertNotNull(name); 
     return context.getResources().getIdentifier(name, //return id 
      "your drawable", context.getPackageName()); 
     } 
     image.setImageResource(int Id);//set id using this method 
2
// take variable of imageview 

private ImageView mImageView; 

//bind imageview with your xml's id 

mImageView = (ImageView)findViewById(R.id.mImageView); 

//set resource for imageview 

mImageView.setImageResource(R.drawable.your_image_name); 
4

而是在你的活動類通過代碼設置繪製資源,你也可以設置在XML佈局:

代碼如下:

<ImageView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:src="@drawable/apple" /> 
0

如果您從Java類

ImageView img = new ImageView(this); 

//Here we are setting the image in image view 
img.setImageResource(R.drawable.my_image); 
1

創建ImageView如果u要設置一個位圖對象這裏圖像視圖是簡單的兩個line`

Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.sample_drawable_image); 
image.setImageBitmap(bitmap); 
相關問題