A word of explanation on this mini-series. I will post a number of short articles presenting various tips I wish I knew when I was starting to code for Android. They might vary from really, really simple and general to highly specialized and pretty complicated. I don’t know yet how many of those tips I will post, and how often I will do that. Be sure to follow me if you want to read them all.
I plan to structure them as follows Tip -> Explanation -> Example(s).
That’s it. Simple and effective.
If you plan on keeping a reference to any ViewGroup (LinearLayout, FrameLayout, RelativeLayout, etc.), and you don’t want to use any methods specific to this particular type of Layout, keep it as a ViewGroup object.
Along the way you will probably make many changes to your layout xml, including changing the actual type of a ViewGroup (e.g. you decide that the FrameLayout is not enough for you anymore and you actually need a RelativeLayout). Keeping a Layout object as a ViewGroup (where possible) will decrease issues with ViewGroup casting, and will make it easier to propagate changes in your layout xml to any classes that are using it.
Important: If you’re using Butterknife (and let’s be honest, you probably are), this kind of error is not something compiler can spot, this blows up in your face during runtime. So if your app has tons of resources and the build/installation time is really, really long, this sort of a bug is especially annoying. Using ViewGroup reference is a really simple way to reduce the time you might be spending on bug tracking.
If you need a reference to a FrameLayout but you don’t need to call any of those methods (FrameLayout-specific methods for API 16):
- generateLayoutParams(AttributeSet attrs)
- setForegroundGravity(int foregroundGravity)
- setMeasureAllChildren(boolean measureAll)
Just keep it as a ViewGroup object.
If your code looks like this:
and you decide to change your FrameLayout to RelativeLayout:
and you didn’t remember to change the exampleLayout field type, that’s what you’ll see (more-less) when you run your app:
A simple trick of using a ViewGroup instead of a FrameLayout for your exampleLayout field, would make you not even have to worry about this kind of stuff in your code.