Search code examples
androidimageviewandroid-imageview

Changing ImageView source


I have an ImageView with a source image set in the xml using the following syntax:

   <ImageView 
      android:id="@+id/articleImg"
      style="@style/articleImgSmall_2"
      android:src="@drawable/default_m" />

Now I need to change this image programmatically. What I need to do is delete the old image and add a new one though. What I have done is this:

myImgView.setBackgroundResource(R.drawable.monkey);

It works but I noticed android stacks the new image on top of the old one (dont ask me how I found out it's not relevant for the discussion :). I definitely need to get rid of the old one before setting the new image.

How can I achieve that?


Solution

  • Changing ImageView source:

    Using setBackgroundResource() method:

      myImgView.setBackgroundResource(R.drawable.monkey);
    

    you are putting that monkey in the background.

    I suggest the use of setImageResource() method:

      myImgView.setImageResource(R.drawable.monkey);
    

    or with setImageDrawable() method:

    myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
    

    *** With new android API 22 getResources().getDrawable() is now deprecated. This is an example how to use now:

    myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
    

    and how to validate for old API versions:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
         myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
       } else {
         myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
    }