2011-02-23 50 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])); 
}