自定义视图案例

基本知识

1、我们在自定义视图View的时候正确的步骤和方法
1)、必须定义有Context/Attrbuite参数的构造方法,并且调用父类的方法
public LabelView(Context context, AttributeSet attrs)
否则会出现bug:
这里写图片描述
2) 当定义宽高属性为wrap_content时,必须onMeasure()来设置view大小.

    @Override  
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
        setMeasuredDimension(measureWidth(widthMeasureSpec),  
                measureHeight(heightMeasureSpec));  
    }  
private int measureWidth(int measureSpec) {  
    int result = 0;  
    int specMode = MeasureSpec.getMode(measureSpec);  
    int specSize = MeasureSpec.getSize(measureSpec);   
    if (specMode == MeasureSpec.EXACTLY) {  
        // We were told how big to be  
        result = specSize;  
    } else {  
        // Measure the text  
        result = (int) mTextPaint.measureText(mText) + getPaddingLeft() + getPaddingRight();  
        if (specMode == MeasureSpec.AT_MOST) {  
            // Respect AT_MOST value if that was what is called for by measureSpec  
            result = Math.min(result, specSize);  
        }  
    }  

    return result;  
}  

3)、重写onTouchEvent方法
获取坐标,计算坐标,然后通过invalidate和postInvalidate方法进行画面的刷新操作即可
关于这两个刷新方法的区别是:invalidate方法是在UI线程中调用的,postInvalidate可以在子线程中调用,而且最重要的是postInvalidate可以延迟调用

例子

第一个例子:自定义LabelView
这个View主要实现的功能和Android中提供的TextView差不多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值