Search code examples
androidandroid-studiodrawableandroid-drawableandroid-resources

Android difference between using ImageResource and Drawable


I am new to Android development and I have originally set my graphics for the user to drag using SetImageResource. However later in development it does not have methods I required so I ended up using SetImageDrawable later on for dragging images and placing them in new spots.

What are the core differences between these two? I have been looking online and am still uncertain on these key differences and how they will affect my program.

Example of how I set the images originally on the view using setImageResource:

case 'J':
    if (tempFlip[9]) {
        GameBoardImages[k].setImageResource(temp[9]);
    } else {
        temp[9] = symbolTilesID[k];
        tempFlip[9] = true;
        GameBoardImages[k].setImageResource(symbolTilesID[k]);
    }
    break;

Then how I have it set in OnDragListener using setImageDrawable:

target = GameBoardImages[ImageNumber]; //Spot getting dragged to

dragged = (ImageView) myDragEvent.getLocalState(); //Dragging item

target_draw = target.getDrawable();
dragged_draw = dragged.getDrawable();

dragged.setImageDrawable(target_draw);
target.setImageDrawable(dragged_draw);

Solution

  • The method setImageResource() takes in a drawable resource ID (which is an int).

    PRO: You are passing in an integer, which is very small in terms of memory. If there are several method calls before your call to setImageResource(), they can easily pass around this int with no memory issues.

    CON: Because you are passing in an integer, the setImageResource() method must perform Bitmap reading and decoding in order to display the image. The method performs this on the UI thread, which could cause a 'latency hiccup' depending on the size of the image and the processing power of the device. This would result in your user seeing a lag or funny behavior on the screen as the image is processed.

    The method setImageDrawable() takes in the actual Drawable object.

    PRO: You already have the actual Drawable, so there is no need to process this data in order to display it. For this method you won't see the latency issues on screen.

    CON: The drawback here is that you might end up passing a drawable around between other methods in order to have access to it to make the setImageDrawable() method call. Passing around Drawable objects a lot isn't a great idea, as they can be large.