如何更改ImageView的图像?

BBd*_*dev 139 android android-imageview

我刚开始学习android.而且我不知道如何更改图像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"/>
Run Code Online (Sandbox Code Playgroud)

感谢回复.

San*_*esh 255

如果您使用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>
Run Code Online (Sandbox Code Playgroud)

第2步:创建一个Activity

ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);
Run Code Online (Sandbox Code Playgroud)

解决方案2:

如果您从Java类创建了imageview

ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);
Run Code Online (Sandbox Code Playgroud)


FrV*_*aBe 40

看看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);
Run Code Online (Sandbox Code Playgroud)

  • 您正在链接到您电脑上的 API 文档:) (2认同)
  • 不要使用评论来提出问题 - 没有人会找到它们,并且您无法接受正确的答案。 (2认同)

小智 14

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

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);
Run Code Online (Sandbox Code Playgroud)

当然,这种技术仅在您需要更改图像时才有用.