自定义View-实现流式布局

public class MyView extends ViewGroup {
int zuo=20;
int shang=20;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int zuoyou = zuo;
    int shangxia = shang;
    for (int i = 0; i < getChildCount() ; i++) {
        int measuredHeight = getChildAt(i).getMeasuredHeight();
        int measuredWidth = getChildAt(i).getMeasuredWidth();
        //换行
        if(measuredWidth+zuo+zuoyou>getWidth()){
            zuoyou =20;
            shangxia+=shang+measuredHeight;
            getChildAt(i).layout(zuoyou,shangxia,zuoyou+measuredWidth,shangxia+measuredHeight);
        }else {
            getChildAt(i).layout(zuoyou,shangxia,zuoyou+measuredWidth,shangxia+measuredHeight);
        }
        zuoyou+=zuo+measuredWidth;
    }
}


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    measureChildren(widthMeasureSpec,heightMeasureSpec);
}

}

你可能感兴趣的:(自用)