android自定义view

本文详细介绍了Android中自定义View的方法,重点讲解了通过继承View并重写onMeasure和onDraw方法来实现自定义View的过程。文章通过示例代码演示了如何根据不同模式设置View尺寸,并在Canvas上绘制元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Android的自定义view有几种,继承View,继承ViewGroup,或者继承特定的布局(例如:LinearLayout),下面介绍继承View这种方式

2.继承View,要重写onMeasure()方法,和onDraw()方法

3.首先是View的测量,onMeasure(int widthMeasureSpec,int heightMeasureSec)方法有两个参数,参数有两种信息,大小和模式

1)MeasureSpec.EXACTLY模式:xml布局的值是match_parent,或者值的大小已经明确;

2)MeasureSpec.AT_MOST模式:xml布局的值是wrap_content

3)MeasureSpec.UNSPECIFIED模式:父控件不强加任何约束给子控件,任何大小都可以

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int defaultSize = 200;//设置一个默认值

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);

    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    if (widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) {
        setMeasuredDimension(widthSize, heightSize);
    } else if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.EXACTLY) {
        setMeasuredDimension(defaultSize, heightSize);
    } else if (widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(widthSize, defaultSize);
    } else {
        setMeasuredDimension(defaultSize, defaultSize);
    }
}

4.接下来重写onDraw()方法,画出想要的view,注意padding

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(5);

        int startX = getPaddingLeft();
        int startY = getMeasuredHeight() / 2;
        int stopX = getMeasuredWidth() - getPaddingRight();
        //画出一条线
        canvas.drawLine(startX, startY, stopX, startY, paint);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值