I just wrote an article for this. I wish you the opportunity to answer your question.
https://plus.google.com/112740367348600290235/posts/VNAfFLDcKrw
ImageView has 4 APIs for specifying an image. Which one to use? What is the difference?
- setImageDrawable (Drawable drawable)
- setImageBitmap (bm bitmap)
- setImageResource (int resId)
- setImageURI (uri uri)
ImageView , by name, is used to display the image. But what is an image? A Bitmap is an image that is not hard to understand, and for this purpose we use setImageBitmap . However, inside << 20> has-a Drawable , but not a Bitmap , and this is what setImageDrawable for. When you call setImageBitmap , internally, first the bitmap will be wrapped in BitmapDrawable , which is IS-A Drawable , and then call setImageDrawable .
Here is the code.
public void setImageBitmap(Bitmap bm) { setImageDrawable(new BitmapDrawable(mContext.getResources(), bm)); }
So what about API 3 and 4?
You should already know that these are bundles of ways to create a bitmap from a file path from a Uri or from a resource file.
BitmapFactory.decodeFile(String pathName) BitmapFactory.decodeStream(Inputstream) BitmapFactory.decodeResource(Resource res, int id) BitmapFactory.decodeByteArray(byte[] data)
Knowing this, it is easy to understand that setImageResource / setImageUri exactly the same as setImageBitmap .
To summarize, setImageDrawable is a primitive function that other APIs rely on. The other 3 are just helper methods that force you to write less code.
In addition, it is very important to keep in mind that ImageView does have-a Drawable , which does not have to be BitmapDrawable ! You can set any Drawable to the image view.
Besides installing Drawable through the Java API, you can also use XML attribution to set the Drawable source for ImageView . See the example below. Please note: the form can be either an image file (.png, .jpg, .bmp) or an xml file.
<ImageView android:layout_width="match_parent" android:layout_height="50dip" android:src="@drawable/shape"/>
shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF" android:angle="270"/> <padding android:left="7dp" android:top="7dp android:right="7dp" android:bottom="7dp" /> <corners android:radius="8dp" /> </shape>