Hello, Android devs! This is my first blog about Android. We know Android SDK provides you a bunch
of useful layouts: FrameLayout, LinearLayout, RelativeLayout, etc. So where is FlowLayout,
which works like a multiline TextView but holding views instead of texts? Developers can just add
views to a FlowLayout and each view is put to the right of the previous one and wraps to a new row
when the current row is full. I’m gonna show you how you could implement your own FlowLayout with
less than 100 lines of code.
Prerequisites
To understand this tutorial, you should have some Android development experience. You should already
know what views and viewgroups are. You also should have used one of the SDK builtin layouts before.
How it works
A layout should subclass
ViewGroup and implement
onMeasure() and onLayout(). onMeasure(int, int) is called when the parent of this view wants
to know this view’s dimension, onLayout(boolean, int, int, int, int) is called when the parent
layouts this view. Since a layout has its own children, it should also layout them in onLayout().
So we basically do two things, calculate the size of the layout in onMeasure() and layout the
children in onLayout().
The code
In onMeasure(), we go through all children, measure each child and put the child to the right of
previous child if there’s enough room for it. Otherwise, wrap the line and put the child to next
line. At last, we know how much room the layout itself want to be to hold all its children.
onLayout() basicly does the same thing except it layouts the children instead of calculating the
dimension.
To make use of our fresh new FlowLayout, put it in an activity and add some views into it.
We add the country name of all locale available on this device into a FlowLayout and see how it
works: