自定义View设置padding和wrap_content无效的解决办法

自定义View设置padding和wrap_content无效的解决办法

当我们使用重写onDraw方法来实现自定义View的时候,发现在xml文件设置自定义View的padding不起作用和设置wrap_content时与match_parent效果一样。其实采用重写onDraw方法自定义View是需要自己支持wrap_content,并且padding也是要自己处理的。举个例子说明一下:使用重写onDraw方法来实现自定义一个实心圆canvas.drawCircle(width / 2, height / 2, radius, mPaint);

  • 对于设置wrap_content属性无效的问题,在自定义View类添加如下重写方法,设置默认值即可。
@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode ==
                MeasureSpec.AT_MOST)
            setMeasuredDimension(200, 200);
        else if (widthSpecMode == MeasureSpec.AT_MOST)     
           setMeasuredDimension(200, heightSpecSize);
       else if (heightSpecMode == MeasureSpec.AT_MOST)
           setMeasuredDimension(widthSpecSize, 200);
    }
  • 对于设置padding值无效的问题,在onDraw方法中获取对应padding的值,然后进行对应的计算即可。
 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int paddingLeft = getPaddingLeft();
        int paddingRight =getPaddingRight();
        int paddingBottom = getPaddingBottom();
        int paddingTop = getPaddingTop();
        int width = getWidth()-paddingLeft-paddingRight;
        int height = getHeight()-paddingBottom-paddingTop;
        float radius = Math.min(width,height)/2;
        canvas.drawCircle(paddingLeft + width/2,paddingTop + height/2,radius,paint);

    }

这里有个问题:为什么margin 不需要自行设置?
这是因为margin属性是由父容器控制的,因此不需要在circleView类中处理。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值