|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, |
|
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 package org.mozilla.gecko.widget; |
|
6 |
|
7 import org.mozilla.gecko.R; |
|
8 |
|
9 import android.content.Context; |
|
10 import android.content.res.TypedArray; |
|
11 import android.util.AttributeSet; |
|
12 import android.view.View; |
|
13 import android.view.ViewGroup; |
|
14 |
|
15 public class FlowLayout extends ViewGroup { |
|
16 private int mSpacing; |
|
17 |
|
18 public FlowLayout(Context context) { |
|
19 super(context); |
|
20 } |
|
21 |
|
22 public FlowLayout(Context context, AttributeSet attrs) { |
|
23 super(context, attrs); |
|
24 TypedArray a = context.obtainStyledAttributes(attrs, org.mozilla.gecko.R.styleable.FlowLayout); |
|
25 mSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_spacing, (int) context.getResources().getDimension(R.dimen.flow_layout_spacing)); |
|
26 a.recycle(); |
|
27 } |
|
28 |
|
29 @Override |
|
30 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { |
|
31 final int parentWidth = MeasureSpec.getSize(widthMeasureSpec); |
|
32 final int childCount = getChildCount(); |
|
33 int rowWidth = 0; |
|
34 int totalWidth = 0; |
|
35 int totalHeight = 0; |
|
36 boolean firstChild = true; |
|
37 |
|
38 for (int i = 0; i < childCount; i++) { |
|
39 final View child = getChildAt(i); |
|
40 if (child.getVisibility() == GONE) |
|
41 continue; |
|
42 |
|
43 measureChild(child, widthMeasureSpec, heightMeasureSpec); |
|
44 |
|
45 final int childWidth = child.getMeasuredWidth(); |
|
46 final int childHeight = child.getMeasuredHeight(); |
|
47 |
|
48 if (firstChild || (rowWidth + childWidth > parentWidth)) { |
|
49 rowWidth = 0; |
|
50 totalHeight += childHeight; |
|
51 if (!firstChild) |
|
52 totalHeight += mSpacing; |
|
53 firstChild = false; |
|
54 } |
|
55 |
|
56 rowWidth += childWidth; |
|
57 |
|
58 if (rowWidth > totalWidth) |
|
59 totalWidth = rowWidth; |
|
60 |
|
61 rowWidth += mSpacing; |
|
62 } |
|
63 |
|
64 setMeasuredDimension(totalWidth, totalHeight); |
|
65 } |
|
66 |
|
67 @Override |
|
68 protected void onLayout(boolean changed, int l, int t, int r, int b) { |
|
69 final int childCount = getChildCount(); |
|
70 final int totalWidth = r - l; |
|
71 int x = 0; |
|
72 int y = 0; |
|
73 int prevChildHeight = 0; |
|
74 |
|
75 for (int i = 0; i < childCount; i++) { |
|
76 final View child = getChildAt(i); |
|
77 if (child.getVisibility() == GONE) |
|
78 continue; |
|
79 |
|
80 final int childWidth = child.getMeasuredWidth(); |
|
81 final int childHeight = child.getMeasuredHeight(); |
|
82 if (x + childWidth > totalWidth) { |
|
83 x = 0; |
|
84 y += prevChildHeight + mSpacing; |
|
85 } |
|
86 prevChildHeight = childHeight; |
|
87 child.layout(x, y, x + childWidth, y + childHeight); |
|
88 x += childWidth + mSpacing; |
|
89 } |
|
90 } |
|
91 } |