2011-02-23 89 views
109

我剛開始學習android。我不知道如何更改ImageView的圖像?即它有一些在佈局中設置的圖像,但我想通過編碼來改變圖像,我應該怎麼做?如何更改ImageView的圖像?

這裏是xml文件

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#cc8181" 
> 

<ImageView 
    android:id="@+id/image" 
    android:layout_width="50dip" 
    android:layout_height="fill_parent" 
    android:src="@drawable/icon" 
    android:layout_marginLeft="3dip" 
    android:scaleType="center"/> 

感謝回答。

+3

你能不能更清楚一點,在你的問題中,我想你可能想動態地在imageView中顯示圖像,例如,當我觸摸並滑動下一個圖像必須顯示,我是嗎? – 2011-02-23 10:00:21

回答

213

如果您使用XML文件,然後按照步驟創建ImageView的。

解決方案1:

第1步:創建一個XML文件

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#cc8181" 
    > 

    <ImageView 
     android:id="@+id/image" 
     android:layout_width="50dip" 
     android:layout_height="fill_parent" 
     android:src="@drawable/icon" 
     android:layout_marginLeft="3dip" 
     android:scaleType="center"/> 

</LinearLayout> 

第2步:創建活動

ImageView img= (ImageView) findViewById(R.id.image); 
img.setImageResource(R.drawable.my_image); 

解決方案2:

如果創建來自Java類的imageview

ImageView img = new ImageView(this); 
img.setImageResource(R.drawable.my_image); 
33

看看ImageView API。有幾種setImage*方法。使用哪一個取決於您提供的圖像。如果你有圖像資源(例如文件RES /繪製/ my_image.png)

ImageView img = new ImageView(this); // or (ImageView) findViewById(R.id.myImageView); 
img.setImageResource(R.drawable.my_image); 
+0

我可以更改屏幕的顏色,通過圖片查看我已經完成 – BBdev 2011-02-23 10:02:45

+1

您鏈接到您的電腦上的API文檔:) – bigstones 2011-02-23 10:03:00

+0

Uups - 固定鏈接。謝謝你告訴我這件事! – FrVaBe 2011-02-23 10:05:47

11

只是去一點點進一步在這個問題上,你也可以直接設置一個位圖,如下所示:

ImageView imageView = new ImageView(this); 
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image); 
imageView.setImageBitmap(bImage); 

當然,如果你需要改變這種技術是唯一有用的圖片。

1
if (android.os.Build.VERSION.SDK_INT >= 21) { 
      storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position], context.getTheme())); 
} else { 
      storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position])); 
}