157

When I change the image programmatically‎, it shows new image on top of the old image which is set originally in layout file?

Here is a snippet of my layout file:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="39dp"
    android:gravity="center_vertical" >
    <ImageView
        android:id="@+id/qStatusImage"
        android:layout_width="16dp"
        android:layout_height="16dp"
        android:layout_margin="5dp"
        android:background="@drawable/thumbs_down"
         />

    <TextView
        android:id="@+id/grp_child"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textColor="@color/radio_colors"
        android:textStyle="normal"
        android:background="@color/grey"
    />

 </LinearLayout>

And the code that sets the imageView:

     @Override
public View getChildView(final int groupPosition, final int childPosition,
        boolean isLastChild, View convertView, ViewGroup parent) {
//Answers
            if(answersGroup != null)
                   answersGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                       @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {

                         //  int index = answersGroup.indexOfChild(findViewById(answersGroup.getCheckedRadioButtonId()));

                           qImageView = (ImageView) V.findViewById(R.id.qStatusImage);
                           if(ans ==0 || ans == 5){
                            //   qSV.setImageResource(0);
                               qImageView.setImageResource(R.drawable.thumbs_up);
                           }
                           else
                               qImageView.setImageResource(R.drawable.thumbs_down);

                       }
                   });

What am I missing?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1529412
  • 3,616
  • 7
  • 26
  • 42

10 Answers10

236

That happens because you're setting the src of the ImageView instead of the background.

Use this instead:

qImageView.setBackgroundResource(R.drawable.thumbs_down);

Here's a thread that talks about the differences between the two methods.

Community
  • 1
  • 1
Voicu
  • 16,921
  • 10
  • 60
  • 69
  • 46
    This doesn't work in API 14. Should use: `image.setImageResource(R.drawable.icon_dot1);` – Brave Sep 03 '15 at 20:45
  • 3
    @Brave's answer is correct. Using `setBackgroundResource()` :( did not remove the existing image before using the new image.. so I got two images colliding there. `setImageResource()` worked tho :). Still .. the post got me on the right track - my thanks for both answers! – Gene Bo Oct 12 '15 at 21:28
  • As the answer by @mricyicy says, the problem is that the xml is defining the background image and the code is changing the resource image. Those are not the same. Setting the resource image is what is actually desired here, so the xml should be fixed. – Martin Epsz Oct 20 '15 at 18:54
  • 3
    Why not `setImageResource`? – Violet Giraffe Aug 09 '16 at 06:45
  • 5
    @VioletGiraffe `ImageView.setImageResource(R.drawable.image);` worked for me – jonasxd360 Jun 27 '18 at 20:43
  • @Brave's answer is more accurate. – Molly Jul 06 '18 at 12:04
  • As @MartinEpsz correctly notes, the XML is the incorrect part here - it's setting the background instead of the src. This answer changes the Java to be incorrect in the same way that the XML is. While this does remove the problem of two images on top of each other, it would be better to fix the XML to set the image via `android:src` instead. – Ryan M Jun 27 '20 at 10:24
102

Use in XML:

android:src="@drawable/image"

Source use:

imageView.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.your_image));
fe_araujo_
  • 1,859
  • 1
  • 14
  • 15
85

Short answer

Just copy an image into your res/drawable folder and use

imageView.setImageResource(R.drawable.my_image);

Details

The variety of answers can cause a little confusion. We have

The methods with Background in their name all belong to the View class, not to ImageView specifically. But since ImageView inherits from View you can use them, too. The methods with Image in their name belong specifically to ImageView.

The View methods all do the same thing as each other (though setBackgroundDrawable() is deprecated), so we will just focus on setBackgroundResource(). Similarly, the ImageView methods all do the same thing, so we will just focus on setImageResource(). The only difference between the methods is they type of parameter you pass in.

Setup

Here is a FrameLayout that contains an ImageView. The ImageView initially doesn't have any image in it. (I only added the FrameLayout so that I could put a border around it. That way you can see the edge of the ImageView.)

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:background="@drawable/border"
        android:layout_centerInParent="true">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </FrameLayout>
</RelativeLayout>

Below we will compare the different methods.

setImageResource()

If you use ImageView's setImageResource(), then the image keeps its aspect ratio and is resized to fit. Here are two different image examples.

  • imageView.setImageResource(R.drawable.sky);
  • imageView.setImageResource(R.drawable.balloons);

enter image description here

setBackgroundResource()

Using View's setBackgroundResource(), on the other hand, causes the image resource to be stretched to fill the view.

  • imageView.setBackgroundResource(R.drawable.sky);
  • imageView.setBackgroundResource(R.drawable.balloons);

enter image description here

Both

The View's background image and the ImageView's image are drawn separately, so you can set them both.

imageView.setBackgroundResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);

enter image description here

Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 2
    note the following about `setImageResource`: `Sets a drawable as the content of this ImageView. This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(Drawable) or setImageBitmap(Bitmap) and android.graphics.BitmapFactory instead.` – William Reed May 30 '20 at 16:07
  • goood explanation @Suragch – gumuruh Dec 06 '20 at 04:22
31
qImageView.setImageResource(R.drawable.img2);

I think this will help you

Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
suraj
  • 641
  • 1
  • 7
  • 15
19

In XML Design

android:background="@drawable/imagename 
android:src="@drawable/imagename"

Drawable Image via code

imageview.setImageResource(R.drawable.imagename);

Server image

  ## Dependency ##

  implementation 'com.github.bumptech.glide:glide:4.7.1'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'

  Glide.with(context).load(url) .placeholder(R.drawable.image)
   .into(imageView);

 ## dependency  ##
 implementation 'com.squareup.picasso:picasso:2.71828'

 Picasso.with(context).load(url) .placeholder(R.drawable.image)
 .into(imageView);
Ashutosh Srivastava
  • 597
  • 1
  • 9
  • 13
14

In your XML for the image view, where you have android:background="@drawable/thumbs_down change this to android:src="@drawable/thumbs_down"

Currently it is placing that image as the background to the view and not the actual image in it.

mricyicy
  • 186
  • 6
3

If the above solutions are not working just delete this entire line from XML

android:src="@drawable/image"

& only try

imageView.setBackgroundResource(R.drawable.image);
H A Tanim
  • 141
  • 1
  • 6
2

You can use

val drawableCompat = ContextCompat.getDrawable(context, R.drawable.ic_emoticon_happy)

or in java java

Drawable drawableCompat = ContextCompat.getDrawable(getContext(), R.drawable.ic_emoticon_happy)
svkaka
  • 3,942
  • 2
  • 31
  • 55
2

In Java, we can change ImageView programmatically like this.

ImageView imageView= (ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.imagename);

In Kotlin,

val imageView: ImageView = findViewById(R.id.imageView)
imageView.setImageResource(R.drawable.imagename)
Samiya Khan
  • 241
  • 3
  • 4
0

This code is working in my case:

imageView.setImageResource(R.drawable.logo)
Abdul Waheed
  • 562
  • 6
  • 14