public fhyxk(Context context) { this(context,null); } public fhyxk(Context context, AttributeSet attrs) { this(context, attrs,0); } public fhyxk(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } private void initView() { } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); measureChildren(widthMeasureSpec,heightMeasureSpec); //定义宽和高 int widthMeasured = 0; int heightMeasured = 0; //获得子view的宽度类型 int Widthmode = MeasureSpec.getMode(widthMeasureSpec); //获得子View的宽度值 int Widthsize = MeasureSpec.getSize(widthMeasureSpec); //获得子view的宽度类型 int Heighthmode = MeasureSpec.getMode(heightMeasureSpec); //获得子View的宽度值 int Heightsize = MeasureSpec.getSize(heightMeasureSpec); switch(Widthmode){ //确定的宽度和match_parent类型的宽高 case MeasureSpec.EXACTLY: widthMeasured=Widthsize; heightMeasured= Heightsize; //wrap_content case MeasureSpec.AT_MOST: int measuredHeight=0; for (int i = 0; i <getChildCount() ; i++) { View childAt = getChildAt(i); measuredHeight = childAt.getMeasuredHeight(); int measuredWidth = childAt.getMeasuredWidth(); widthMeasured+=measuredWidth; } heightMeasured+=measuredHeight; break; case MeasureSpec.UNSPECIFIED: break; } } public int oritation = 2; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int topAll = 0; int leftAll = 0; int marginLeft = 48; int marginTop = 48; for (int i = 0; i < getChildCount(); i++) { View childAt = getChildAt(i); int width = childAt.getMeasuredWidth(); int height = childAt.getMeasuredHeight(); // childAt.layout(0, topAll, 0 + width, topAll + height); if(oritation == 0) { childAt.layout(0, topAll, 0 + width, topAll + height); topAll += height+marginTop; //横向 }else if (oritation == 1) { childAt.layout(leftAll+18, marginTop, leftAll + width+30, height +marginTop); // childAt.layout(100, 100, 100, 100); leftAll += width+marginLeft; }else if (oritation ==2){ childAt.layout(leftAll, topAll, 0 + width+leftAll, topAll + height); topAll += height+marginTop; leftAll += width+marginLeft; } } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); }
自定义View实现横,纵,斜向视图
最新推荐文章于 2021-05-26 00:47:27 发布