自定义view关于wrapcontent,margin,padding的处理。

image.png

自定义view

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        int size = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        if(mode == MeasureSpec.AT_MOST){
            setMeasuredDimension(500,heightSize);
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();

        int paddingLeft = getPaddingLeft();
       int paddingRight = getPaddingRight();
        int paddingBottom = getPaddingBottom();
        int paddingTop = getPaddingTop();

        canvas.drawCircle((width+paddingLeft-paddingRight)/2,(height-paddingBottom+paddingTop)/2,Math.min((width-paddingLeft-paddingRight)/2,(height-paddingBottom-paddingTop)/2),paint);

    }

自定义viewgroup,对onMeasure和onLayout的处理

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //假设这是一个linearlayout vertical 具体情况具体讨论
        //
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        
        measureChildren(widthMeasureSpec,heightMeasureSpec);
        //调用了measureChild 里面合成了view的MeasureSpec,然后view调用了measure
        //如果mode 是EXACTLY  按照自己的size去设置 这里不写了
        //如果是AL_MOST 遍历子元素,宽度是最大子元素宽度,高度是所有子元素加起来的高度。

        //1.判断子元素数量 //2.遍历子元素 获取宽高 //3.给viewgroup设置宽高
        int childCount = getChildCount();
        //如果是0 直接宽高设为0
        //如果不是
        int viewMeasurHeight = 0;
        int viewMeasuredWidth = 0;
        for (int i =0;i
   @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //还是以onMeasure做假设的 线性布局,Vertical
        //每一个view 从上到下排列。x坐标不变,y坐标一直变大。

        int childCount = getChildCount();
        for (int i = 0;i
public MyVIewCircle(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyVIewCircle);
        int color = typedArray.getColor(R.styleable.MyVIewCircle_color, Color.RED);
        typedArray.recycle();
        init();
    }

你可能感兴趣的:(自定义view关于wrapcontent,margin,padding的处理。)