It is advantageous in my application if I preload certain images. I do this correctly, in AsyncTask, as it is written in the official documentation. But I have a problem/question about when they should be set.
I’ll show code snippets. Note that it’s simplified (their interoperability is better in my real code, it checks for nulls, etc.).
Let’s see the original (non-preloaded) version first:
<ImageView
android:id="@+id/imageViewMyGraphicalImageElement"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop"
android:src="@drawable/my_graphical_element" >
</ImageView>
The preloaded version has the following XML (notice that the src attribute is missing):
<ImageView
android:id="@+id/imageViewMyGraphicalImageElement"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop">
</ImageView>
And a snippet from the preload code:
sBitmap = bitmapBitmapFactory.decodeResource(context.getResources(), R.drawable.my_graphical_element, options);
// 'sBitmap' is a Bitmap reference, while 'options' is BitmapFactory.Options
Finally, the place where I set it:
setContentView(R.layout.main);
...
ImageView imageViewMyGraphicalImageElement= (ImageView) findViewById(R.id.imageViewMyGraphicalImageElement);
imageViewMyGraphicalImageElement.setImageBitmap(sBitmap);
Question:
Obviously, the xml-based solution knows about the image before setContentView(…) is called. The preload version sets the image after that call. Is there any difference? Can some autoscaling or other things done by the system be skipped due to this?
There is no difference at all. You can consider that all the
ImageViewconstructor does with theandroid:srcattribute is callsetImageResource.Update: Actually it uses
setImageDrawable, this is the actual code forImageViewconstructor taking attributes:Reference: ImageView.java