自定义View(1)

来源:互联网 发布:淘宝双十一利弊 编辑:程序博客网 时间:2024/06/05 05:20

1. 自定义view属性

<resources>    <declare-styleable name="MyView">        <attr name="titleText" format="string" />        <attr name="titleTextColor" format="color" />        <attr name="titleTextSize" format="dimension" />    </declare-styleable></resources>

2. 构造函数中获取属性

<span style="white-space:pre"></span>TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);        mTitleText = a.getString(R.styleable.MyView_titleText);        mTitleTextColor = a.getColor(R.styleable.MyView_titleTextColor, Color.BLACK);        mTitleTextSize = a.getDimensionPixelSize(R.styleable.MyView_titleTextSize, 16);        a.recycle();
3. 重写<span style="font-family: Consolas; font-size: 10.5pt; background-color: rgb(255, 255, 255);">onMeasure</span>
<span style="font-family: Consolas; font-size: 10.5pt; background-color: rgb(255, 255, 255);"></span><pre name="code" class="java">@Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int widthMode = MeasureSpec.getMode(widthMeasureSpec);        int heightMode = MeasureSpec.getMode(heightMeasureSpec);        int widthSize = MeasureSpec.getSize(widthMeasureSpec);        int heightSize = MeasureSpec.getSize(heightMeasureSpec);        int width;        int height;        if (widthMode == MeasureSpec.EXACTLY) {            width = widthSize;        } else {            mPaint.setTextSize(mTitleTextSize);            mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);            width = getPaddingLeft() + mBound.width() + getPaddingRight();        }        if (heightMode == MeasureSpec.EXACTLY) {            height = heightSize;        } else {            mPaint.setTextSize(mTitleTextSize);            mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);            height = getPaddingTop() + mBound.height() + getPaddingBottom();        }        setMeasuredDimension(width, height);    }


4 重写OnDraw

@Override    protected void onDraw(Canvas canvas) {        mPaint.setColor(Color.YELLOW);        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);        mPaint.setColor(mTitleTextColor);        canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);    }



0 0
原创粉丝点击