在此之前都所使用的的布局都是第三方的,看了一些资料,自己稍微修改了下,今天借此机会来实现一个简单的流式布局,左对齐,右对齐和 居中三种模式。作为一个little tinny note吧,哈哈哈!
大致的实现思路:
1.继承ViewGroup重写onMeasure()和onLayout()方法;
2.在onMeasure()方法中测量所有子View的宽和高,此处会使用一个List来存储每一行所能放置的最大子View数量,并且记录下每一行所需要的宽度;方便后续在onLayout()方 法中进行布局。
3.在onLayout()方法中,根据设定的模式(setDefaultDisplayMode()方法包含两种模式:
//靠左放置标签
public static final int START_FROM_LEFT = 1;
//居中放置标签
public static final int START_FROM_CENTER = 0;
//靠右放置标签
public static final int START_FROM_RIGHT = -1;
效果图:
1.
2.
3.
贴代码代码:
1.自定义标签布局SQLFlowLayout类(继承自ViewGroup)
public class SQLFlowLayout extends ViewGroup { //靠左放置标签 public static final int START_FROM_LEFT = 1; //居中放置标签 public static final int START_FROM_CENTER = 0; //靠右放置标签 public static final int START_FROM_RIGHT = -1; private int lineMode = START_FROM_LEFT; // 水平间距,单位为px private int horizontalSpacing = 25; // 竖直间距,单位为px private int verticalSpacing = 45; // 行集合 private List<Line> lines = new ArrayList<Line>(); // 当前的行 private Line line; // 当前行使用的空间 private int lineUsedSize = 0; public void setDefaultDisplayMode(int lineMode) { this.lineMode = lineMode; } public SQLFlowLayout(Context context) { super(context); } public SQLFlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } public SQLFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * 计算出所有子控件的宽和高,从而确定当前父布局的宽和高 * * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 实际可以用的宽和高(去除 padding 内边距) int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingBottom() - getPaddingTop(); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); // Line初始化 restoreLine(); initLine(); for (int count = getChildCount(), i = 0; i < count; i++) { View child = getChildAt(i);