自动根据控件排序布局

来源:互联网 发布:林彪为什么要叛变 知乎 编辑:程序博客网 时间:2024/04/30 09:57
/**
* 本来想找个能根据内容实现自动布局排序的,结果试了一下不如人意,每次用都得刷新数组,会有闪屏!
* 所以就在原来基础上修改了下代码!
*/
public class AutoWrapLinearLayout extends LinearLayout {private int mWidth;//AutoWrapLinearLayout控件的宽private int mHeight;//AutoWrapLinearLayout控件的高private int r;private int l;static final String TAG = "AutoWrapLinearLayout";    public AutoWrapLinearLayout(Context context){super(context);}public AutoWrapLinearLayout(Context context,AttributeSet attrs){super(context,attrs);}@Overrideprotected void onLayout(boolean changed,int l,int t,int r,int b){    this.r=r;    this.l=l;}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){int cellWidthSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);//让自控件自己按需撑开int cellHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);//让自控件自己按需撑开int count = getChildCount();for(int i = 0;i<count; i++){View childView = getChildAt(i);try {childView.measure(cellWidthSpec, cellHeightSpec);}catch(NullPointerException e){//这个异常不影响展示}}                foo();setMeasuredDimension(resolveSize(mWidth, widthMeasureSpec), resolveSize(mHeight, heightMeasureSpec));}private void foo(){mWidth = r-l;//宽度是跟随父容器而定的//自身控件的paddingint paddingLeft = getPaddingLeft();int paddingRight = getPaddingRight();int paddingTop = getPaddingTop();int paddingBottom = getPaddingBottom();//控件自身可以被用来显示自控件的宽度int mDisplayWidth = mWidth - paddingLeft - paddingRight;//自控件的marginint cellMarginLeft = 0;int cellMarginRight = 0;int cellMarginTop = 0;int cellMarginBottom = 0;int x = 0;//子控件的默认左上角坐标xint y = 0;//子控件的默认左上角坐标yint totalWidth = 0;//计算每一行随着自控件的增加而变化的宽度int count = getChildCount();int cellWidth = 0;//子控件的宽,包含paddingint cellHeight = 0;//自控件的高,包含paddingint left = 0;//子控件左上角的横坐标int top = 0;//子控件左上角的纵坐标LayoutParams lp;for(int j=0;j<count;j++){final View childView = getChildAt(j);//获取子控件child的宽高cellWidth = childView.getMeasuredWidth();//测量自控件内容的宽度(这个时候padding有被计算进内)cellHeight = childView.getMeasuredHeight();//测量自控件内容的高度(这个时候padding有被计算进内)lp = (LayoutParams) childView.getLayoutParams();cellMarginLeft = lp.leftMargin;cellMarginRight = lp.rightMargin;cellMarginTop = lp.topMargin;cellMarginBottom = lp.bottomMargin;//动态计算子控件在一行里面占据的宽度//预判,先加上下一个要展示的子控件,计算这一行够不够放totalWidth += cellMarginLeft + cellWidth + cellMarginRight;if(totalWidth >= mDisplayWidth){//不够放的时候需要换行y += cellMarginTop + cellHeight + cellMarginBottom;//新增一行totalWidth = cellMarginLeft + cellWidth + cellMarginRight;//这时候这一行的宽度为这个子控件的宽度x = 0;//重置}//计算顶点横坐标left = x + cellMarginLeft + paddingLeft;//计算顶点纵坐标top = y + cellMarginTop + paddingTop;//绘制自控件childView.layout(left, top, left + cellWidth, top + cellHeight);//计算下一个横坐标x += cellMarginLeft + cellWidth + cellMarginRight;}mHeight = paddingTop + y + cellMarginTop + cellHeight + cellMarginBottom + paddingBottom;}}

0 0
原创粉丝点击