XML vs. setImageDrawable/setImageBitmap

android, android-layout, drawable, java

Solution

There is no difference at all. You can consider that all the `ImageView` constructor does with the `android:src` attribute is call `setImageResource`.

Update: Actually it uses `setImageDrawable`, this is the actual code for `ImageView` constructor taking attributes:

    Drawable d = a.getDrawable(com.android.internal.R.styleable.ImageView_src);
    if (d != null) {
        setImageDrawable(d);
    }

Reference: ImageView.java

Problem

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?

Original source