Если вы хотите, чтобы контейнер ваших тегов в конечном итоге прокручивался, используйте RecyclerView и GridLayoutManager и позвоните по нему setSpanCount(3)
. Не забудьте установить ориентацию на VERTICAL
Если Yout не будет когда-нибудь понадобится ваши элементы будут прокрутки, а затем просто использовать GridLayout
EDIT:
Я поставил вместе грубый пример, который работает в как вы хотите. Вам, вероятно, потребуется также учитывать маржу и дополнение, но она должна служить вам в качестве базовой идеи, как это сделать.
public class TagLayout extends ViewGroup {
public TagLayout(Context context) {
super(context);
}
public TagLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TagLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public TagLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int maxWidth = getMeasuredWidth();
int count = getChildCount();
int tagLeft = left,
tagTop = top,
tagRight = 0,
tagBottom = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
tagRight = tagLeft + child.getMeasuredWidth();
tagBottom = tagTop + child.getMeasuredHeight();
if (tagRight > maxWidth) {
tagLeft = left;
tagRight = left + child.getMeasuredWidth();
tagTop = tagBottom;
tagBottom += child.getMeasuredHeight();
}
child.layout(tagLeft, tagTop, tagRight, tagBottom);
tagLeft = left;
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = 0;
int height = 0;
int count = getChildCount();
int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
width += child.getMeasuredWidth();
if (height == 0) {
height += child.getMeasuredHeight();
}
if (width <= maxWidth) {
continue;
} else {
width = 0;
height += child.getMeasuredHeight();
}
}
}
setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
}
Почему бы не использовать сетку? – Skynet
См. Править, почему это невозможно. – Mehdiway
То, что вы описываете, обычно называется FlowLayout. Здесь есть несколько [несколько сообщений] (http://stackoverflow.com/search?q=%5Bandroid%5D+flow+layout), которые могут помочь вам. –