Android自定义View训练【2】

前言:最近这段时间想根据网上博客的案例,自己练习自定义View,代码仅仅作为练习用,还有很多不足之处,见谅

案例取自:http://blog.csdn.net/wingichoy/article/details/50460213


自定义View代码:

public class PracticeView2 extends View {

    private Paint mPaint = new Paint();
    private Path mpath = new Path();
    private int mCount = 10;
    private int mwidth = 180;
    private int mheight = 200;
    private float msize = 0;
    private int mode;
    private int mColor;

    public PracticeView2(Context context) {
        this(context, null);
    }

    public PracticeView2(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PracticeView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.view2, defStyleAttr, 0);
        mColor = array.getColor(R.styleable.view2_color, Color.BLUE);
        //mColor = Color.BLUE;
        mPaint.setColor(mColor);
        mode = array.getInteger(R.styleable.view2_mode, 2);
        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int mwidthmode = MeasureSpec.getMode(widthMeasureSpec);
        int mwidthsize = MeasureSpec.getSize(widthMeasureSpec);
        int mheightmode = MeasureSpec.getMode(heightMeasureSpec);
        int mheightsize = MeasureSpec.getSize(heightMeasureSpec);

        mwidth = mwidthsize;
        mheight = mheightsize;

        if (mwidthmode == MeasureSpec.AT_MOST) {
            mwidth = 180;
        }
        if (mheightmode == MeasureSpec.AT_MOST) {
            mheight = 250;
        }

        setMeasuredDimension(mwidth, mheight);
        Log.d("SunJ", "宽度:" + mwidth + "   高度:" + mheight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);

        if (mode == 1) {
            msize = mheight/(2f*mCount);
            Log.d("SunJ", "边长:" + msize);
            canvas.drawRect(msize, 0, mwidth-msize, mheight, mPaint);
            for(int i=0; i

activity的布局文件:




    

    




自定义属性xml文件:




    
        
        
            
            
        
    



显示:

Android自定义View训练【2】_第1张图片


最后,做总结:

1.重写View的四大步骤:

        ①自定义View属性

        ②在View的构造方法中获得自定义的View属性

        ③重写onMeasure()方法

        ④重写onDraw()方法


你可能感兴趣的:(Android自定义View训练【2】)