android - Changing ImageView source

ID : 10316

viewed : 21

Tags : androidimageviewandroid-imageviewandroid

Top 5 Answer for android - Changing ImageView source

vote vote

92

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)); } 
vote vote

90

You're supposed to use setImageResource instead of setBackgroundResource.

vote vote

77

myImgView.setImageResource(R.drawable.monkey); 

is used for setting image in the current image view, but if want to delete this image then you can use this code like:

((ImageView) v.findViewById(R.id.ImageView1)).setImageResource(0); 

now this will delete the image from your image view, because it has set the resources value to zero.

vote vote

69

get ID of ImageView as

ImageView imgFp = (ImageView) findViewById(R.id.imgFp); 

then Use

imgFp.setImageResource(R.drawable.fpscan); 

to set source image programatically instead from XML.

vote vote

57

Or try this one. For me it's working fine:

imageView.setImageDrawable(ContextCompat.getDrawable(this, image)); 

Top 3 video Explaining android - Changing ImageView source

Related QUESTION?