Issue
What are the pros and cons between the two scenarios below:
Using a LayoutView (such as RelativeLayout/LinearLayout) and invoking setBackground(drawable) with a Drawable object
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?
Solution
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, usingImageView
XML
attributes. - In approach #2, you will have to worry about managing your
ImageView
and other possible childViews
of yourLayoutView
(relative positions, sizes, order), because they will be related in one way or another. In approach #1, yourLayoutView
background will never mess around with the childViews
. - In terms of code legibility, seeing a
RelativeLayout
with a childImageView
whose only function is defining a background does not make sense, unless it is a very special case. You have theandroid: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.
Answered By - joao2fast4u
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.