How can I change the image of an ImageView?

BBdev picture BBdev · Feb 23, 2011 · Viewed 438.6k times · Source

I have just started learning android. And i don't know How can I change the image of an ImageView? ie it has some Image which was set in the layout but i want to change that image through coding how should i do it ?

Here is the xml file

<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"/>

thanks for replying.

Answer

Sankar Ganesh PMP picture Sankar Ganesh PMP · Feb 23, 2011

If you created imageview using xml file then follow the steps.

Solution 1:

Step 1: Create an XML file

<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>

Step 2: create an Activity

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

Solution 2:

If you created imageview from Java Class

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