author:Created by WeiWeiFeng on 2018/4/14. */ public class HorizontalView extends ViewGroup { int mLeft=20; int mTop=10; public HorizontalView(Context context) { this(context,null); } public HorizontalView(Context context, AttributeSet attrs) { this(context, attrs,0); } public HorizontalView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); measureChildren(widthMeasureSpec, heightMeasureSpec); int viewWidth=0; int viewHeigth=0; int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int modeHeigth = MeasureSpec.getMode(heightMeasureSpec); int sizeHeigth = MeasureSpec.getSize(heightMeasureSpec); switch(modeWidth){ case MeasureSpec.AT_MOST: //自适应 for (int i = 0; i < getChildCount(); i++) { View childAt = getChildAt(i); int measuredWidth1 = childAt.getMeasuredWidth(); viewWidth+=measuredWidth1+mLeft; } viewHeigth+=mLeft*2-10; break; case MeasureSpec.EXACTLY: viewWidth=sizeWidth; break; } switch(modeHeigth){ case MeasureSpec.AT_MOST: View childAt = getChildAt(0); int childAtMeasuredHeight = childAt.getMeasuredHeight(); viewHeigth=childAtMeasuredHeight+mTop*2; break; case MeasureSpec.EXACTLY: viewHeigth=sizeHeigth; break; } setMeasuredDimension(viewWidth,viewHeigth); } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) { int left=mLeft; int top=mTop; int maginLeft=10; for (int j = 0; j < getChildCount(); j++) { View childAt = getChildAt(j); childAt.layout(left,top,childAt.getMeasuredWidth()+left,childAt.getMeasuredHeight()+top); left+=childAt.getMeasuredWidth()+maginLeft; } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } }
自定义View 实现横向的搜索记录
最新推荐文章于 2021-05-25 18:29:16 发布