Difference between setImageResource and setImageDrawable

Asked

Viewed 3,930 times

5

To set an image in Imageview I did as follows using the setImageDrawable:

imagem.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.cliente));

While searching for Imageview I also found the method setImageResource and it also worked that way:

 imagem.setImageResource(R.drawable.cliente);

However I did not find the difference between the methods and which one I should use in this situation, that depending on one information from another the method arrow the corresponding image.

3 answers

4


The purpose of the two methods is the same: to assign the content to the Imageview. The difference is only in the type that each of the methods receives.

In addition to these, the Imageview provides other methods with the same purpose and that receive other types:

Which one to use will depend on the type you have available at the time.

From what is implied is a Resource Id which is available, then should be used imagem.setImageResource(R.drawable.cliente);. Besides, how is a int, it is easy to pass it to another Activity, as seems to be the case.

2

The way you’re doing, none, because you’re converting a Source into a Drawable. But Drawables don’t have to come from Resources: they can come from local files on the device, the Internet, an XML, they can be generated by some algorithm etc.

In short: setImageResource is for images that are in your Resources and setImageDrawable is for any Drawable, from wherever it has come.

0

To documentation of setImageResource says that it reads and decodes Bitmap in the UI thread. So this method is slower than setImageDrawable. The documentation suggests the use of setImageDrawable instead of setImageResource.

The methods are different and setImageDrawable is more performatic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.