1. 程式人生 > >android自定義控制元件--學習

android自定義控制元件--學習

public class MyView extends View {
    private String TAG="MyView";    private Paint mPaint;   //畫筆
private RectF oval;
    public MyView(Context context) {
        super(context);
        init();
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public 
MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } /** * 初始化 */ private void init() { mPaint=new Paint(); // 設定Paint為無鋸齒 mPaint.setAntiAlias(true); oval=new RectF(); } //測量 @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthMode=MeasureSpec.getMode(widthMeasureSpec); int widthSize=MeasureSpec.getSize(widthMeasureSpec); int heightMode=MeasureSpec.getMode(heightMeasureSpec); int
heightSize=MeasureSpec.getSize(heightMeasureSpec); switch (widthMode){ case MeasureSpec.AT_MOST: //子容器可以是宣告大小內的任意大小. break; case MeasureSpec.EXACTLY: //父容器已經為子容器設定了尺寸,子容器應當服從這些邊界,不論子容器想要多大的空間. break; case MeasureSpec.UNSPECIFIED: //父容器對於子容器沒有任何限制,子容器想要多大就多大. break; } Log.e(TAG, "onMeasure--widthSize-->" + widthSize); Log.e(TAG, "onMeasure--heightMode-->" + heightMode); Log.e(TAG, "onMeasure--heightSize-->" + heightSize); } //畫的位置 @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); Log.e(TAG, "onLayout"); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint.setColor(Color.BLUE); int with=getWidth(); int height=getHeight(); mPaint.setStyle(Paint.Style.FILL); // 畫一個正放形 前面兩個是左上角座標 後面兩個是右下角座標 canvas.drawRect(0,20,30,50,mPaint); }