153

我刚开始学习安卓。而且我不知道如何更改图像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"/>

感谢回复。

4

4 回答 4

288

如果您使用 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);
于 2011-02-23T10:08:05.160 回答
44

看看ImageView API。有几种setImage*方法。使用哪一个取决于您提供的图像。如果您将图像作为资源(例如文件 res/drawable/my_image.png)

ImageView img = new ImageView(this);  // or (ImageView) findViewById(R.id.myImageView);
img.setImageResource(R.drawable.my_image);
于 2011-02-23T10:01:42.253 回答
16

只是为了更进一步,您也可以直接设置位图,如下所示:

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

当然,此技术仅在您需要更改图像时才有用。

于 2013-12-05T19:50:58.557 回答
3
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]));
}
于 2016-08-09T15:35:43.683 回答