自定义View---继承View

  • 继承View重写onDraw的同时,还需要注意2点
    • 1.该控件在布局中用wrap_content的时候
    • 2.该控件用padding的时候
  • 问题一:如果用了wrap_content则需要重写onMeasure方法!进行判断
    private int mHeight = 200;
    private int mWidth = 200;
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //得到宽高的各自模式和大小
        int width_mode = MeasureSpec.getMode(widthMeasureSpec);
        int width_size = MeasureSpec.getSize(widthMeasureSpec);
        int height_mode = MeasureSpec.getMode(heightMeasureSpec);
        int height_size = MeasureSpec.getSize(heightMeasureSpec);
        //判断如果2个都是指定wrap_content就默认指定一个宽高的大小,这个可以自定义
        if (width_mode == MeasureSpec.AT_MOST && height_mode == MeasureSpec.AT_MOST){
            setMeasuredDimension(mWidth , mHeight);
            //如果宽是wrap_content就默认一个宽度,高还是系统的值
        }else if (width_mode == MeasureSpec.AT_MOST  ){
            setMeasuredDimension(mWidth , height_size);
           // 如果高是wrap_content就默认一个高度
        }else if (height_mode == MeasureSpec.AT_MOST ){
            setMeasuredDimension(width_size , mHeight);
        }
    }
  • 问题二:然后就是padding的问题
    • 这个需要根据具体逻辑来使用,不过代码大体一样
 @Override
 protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //先得到padding的各自值
        int paddingBottom = getPaddingBottom();
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        //然后在需要用到宽高的地方减去相对应的padding值
        int width = getWidth()-paddingLeft - paddingRight;
        int height = getHeight()-paddingTop - paddingBottom;
        int radius = Math.min(width, height) / 2;
        //在绘制的时候在加上相应的padding值
        canvas.drawCircle(width/2 + paddingLeft, height/2 + paddingTop, radius , mPaint);
    }
  • 上面2个问题主要就是针对布局文件中的属性来展开的
 <xingao.com.ui.CircleView
        android:id="@+id/cv_view"
        android:layout_width="wrap_content"//问题一
        android:layout_height="100dp"
        android:padding="10dp"//问题二
        />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值