Layout

来源:互联网 发布:淘宝被盗号了怎么办 编辑:程序博客网 时间:2024/06/05 23:50

Measure 过程最终确定的是 measureWidth 和 measureHeight。

Layout 过程确定 mLeft, mTop, mRight 和 mBottom,这 4 个值是相对坐标(相对于父 View)。

实现 ViewGroup 需要实现 onLayout 函数。

  @Override    protected abstract void onLayout(boolean changed,            int l, int t, int r, int b);


实现了一个 FlowLayout,还是有理解不足的地方。


public class SimpleFlowLayout extends ViewGroup {    public SimpleFlowLayout(Context context) {        super(context);    }    public SimpleFlowLayout(Context context, AttributeSet attrs) {        super(context, attrs);    }    public SimpleFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    SparseIntArray tops = new SparseIntArray();    SparseIntArray lefts = new SparseIntArray();    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        // 只处理 EXACTLY MODE        if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {            int parentWidth = MeasureSpec.getSize(widthMeasureSpec);            measureChildren(widthMeasureSpec, heightMeasureSpec);            int left = 0;            // 一行的高度            int lineHeight = 0;            int previousLineHeight = 0;            for (int i = 0; i != getChildCount(); i++) {                View child = getChildAt(i);                int childWidth = child.getMeasuredWidth();                int childHeight = child.getMeasuredHeight();                if (left + childWidth < parentWidth) {                    lefts.put(i, left);                    tops.put(i, previousLineHeight);                    left += childWidth;                    lineHeight = Math.max(lineHeight, childHeight);                } else {                    previousLineHeight = lineHeight;                    lineHeight = 0;                    left = 0;                    i--;                }            }            super.onMeasure(widthMeasureSpec, heightMeasureSpec);        }    }    @Override    protected void onLayout(boolean changed, int l, int t, int r, int b) {        for (int i = 0; i != getChildCount(); i++) {            View child = getChildAt(i);            int childWidth = child.getMeasuredWidth();            int childHeight = child.getMeasuredHeight();            int left = lefts.get(i);            int top = tops.get(i);            child.layout(left, top, left + childWidth, top + childHeight);        }    }}

推荐文章

http://www.cnblogs.com/xyhuangjinfu/p/5435253.html


0 0