Android 自定义View

996 阅读1分钟

Android 自定义View

自定义View
    // new 的时候调用
    public XXXView(Context context) {
        super(context);
    }
		// layout 文件中使用的时候会调用 ,attrs 是它的所有属性
    public XXXView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public XXXView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
		// API 21 添加
    public XXXView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int             
    defStyleRes) {               
        super(context, attrs, defStyleAttr, defStyleRes);
    }
    
    
    // 在 activity 中使用
    XXXView xx = new XXXView(this);
    
    
    // 在 layout 文件中使用  包名.XXXView
    <com.xxx.xxx.XXXView
    // android View 属性
    />
    
onMeasure

View的大小不仅由自身所决定,同时也会受到父控件的影响,测量View大小使用onMeasure函数

   @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);      //取出宽度的确切数值
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);      //取出宽度的测量模式
        
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);    //取出高度的确切数值
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);    //取出高度的测量模式
    }
    
    //mode
    UNSPECIFIED 默认值,父控件没有给子view任何限制,子View可以设置为任意大小。
    EXACTLY     表示父控件已经确切的指定了子View的大小。
    AT_MOST     表示子View具体大小没有尺寸限制,但是存在上限,上限一般为父View大小。
    
onSizeChanged

这个函数在视图大小发生改变时调用

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }
onDraw

onDraw是实际绘制的部分,也就是我们真正关心的部分,使用的是Canvas绘图

		@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        
        getLeft(); 
        getRight();
        getTop(); 
        getBottom();
        
        Paint paint = new Paint();
        paint.setColor(Color.BLUE);
        
    }