Android自定义控件-AddView

package view;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class AddView extends View{
    private int STATUS = 1;
    private final int DOWN = 1, UP = 2;
    private OnClickListener listener = null;
    public AddView( Context cxt ) {
        super( cxt );
        initEvent();
    }
    public AddView( Context cxt, AttributeSet attrs ){
        super( cxt, attrs );
        initEvent();
    }
    public AddView( Context cxt, AttributeSet attrs, int style ){
        super( cxt, attrs, style );
        initEvent();
    } 
    @SuppressWarnings("deprecation")
    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setAntiAlias( true );
        if( STATUS == UP ){
            paint.setColor( getResources().getColor(R.color.theme_color) );
        }else if( STATUS == DOWN ){
            paint.setColor( Color.GRAY );
        }

        int width = getWidth(),
            height = getHeight();
        canvas.drawCircle( width/2, width/2, width/2, paint);
        paint.setColor( Color.WHITE );
        int w = width * 7 / 10;
        int h = 10;
        RectF rect = new RectF();
        rect.left = width/2-w/2;
        rect.top = height/2-h/2;
        rect.right = width/2+w/2;
        rect.bottom = height/2+h/2;
        canvas.drawRoundRect( rect, 4, 4, paint);
        rect.left = width/2-h/2;
        rect.top = height/2-w/2;
        rect.right = width/2+h/2;
        rect.bottom = height/2+w/2;
        canvas.drawRoundRect( rect, 4, 4, paint);
    }
    private void initEvent(){
        STATUS = UP;
        this.setOnTouchListener( new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                switch( event.getAction() ){
                case MotionEvent.ACTION_DOWN:
                    STATUS = DOWN;
                    invalidate();
                    break;
                case MotionEvent.ACTION_CANCEL:
                    STATUS = UP;
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    STATUS = UP;
                    invalidate();
                    if( listener != null ){
                        listener.onClick();
                    }
                    break;
                }
                return true;
            }
        } );
    }
    public void setOnTouchListener( OnTouchListener l ){
        listener = l;
    }
    public interface OnTouchListener{
        public void onTouch();
    }

}

你可能感兴趣的:(Android自定义)