code
code

Reputation: 5642

Should we set background in LayoutView or ImageView in Android?

What are the pros and cons between the two scenarios below:

  1. Using a LayoutView (such as RelativeLayout/LinearLayout) and invoking setBackground(drawable) with a Drawable object

  2. Using an ImageView (width: fill_parent, height: fill_parent) inside of a LayoutView and invoking the following:

    • imageView.setBackground(drawable)
    • imageView.setBackgroundResource(resource)
    • imageView.setImageBitmap(bitmap)
    • imageView.setImageResource(stub_id)

Is approach #2 better performance? And if so, which would be the recommended way of setting the background for an ImageView?

Upvotes: 2

Views: 637

Answers (1)

joao2fast4u
joao2fast4u

Reputation: 6892

I would stick with approach #1, if I just wanted to have a simple background for my layout. Note that you have more than just that method you are referring for applying a background over a LayoutView, like:

myLayout.setBackgroundColor(int color);
myLayout.setBackgroundDrawable(Drawable d);
myLayout.setBackgroundResource(int resid);

Now, the reasons for choosing approach #1:

  • Android will only inflate one View, not two, like it would have to in approach #2
  • Android will automatically size your image/drawable/bitmap to the LayoutView size. In approach #2, that task would have to be executed by yourself, using ImageView XML attributes.
  • In approach #2, you will have to worry about managing your ImageView and other possible child Views of your LayoutView (relative positions, sizes, order), because they will be related in one way or another. In approach #1, your LayoutView background will never mess around with the child Views.
  • In terms of code legibility, seeing a RelativeLayout with a child ImageView whose only function is defining a background does not make sense, unless it is a very special case. You have the android:background attribute for that. In this case, less code makes better code.
  • In code, in approach #2 you have to declare two views and, thus, more memory will be required to apply the methods on those Views. In approach #1, you can do what you need in 3 lines of code.

Seems like there are more than enough reasons for using approach #1.

For the second part of your question, the best way of setting a background with a Drawable depends on the origin of that Drawable (from resources, generated Drawable object, etc) and what you want to do with that Drawable (passing it to Bitmap and make some changes, etc).

You can check the documentation for each of those methods to better understand when you should use each of them.

Upvotes: 1

Related Questions