舉個(gè)例子椭蹄,當(dāng)我們繼承View來(lái)實(shí)現(xiàn)一個(gè)自定義view時(shí)坊萝,重寫onDraw方法宋下,畫一個(gè)圓咙好,canvas.drawCircle(width / 2, height / 2, radius, mPaint);當(dāng)我們?cè)诓季种惺褂脮r(shí),對(duì)其加上padding屬性:padding=10;會(huì)發(fā)現(xiàn)padding屬性根本不起作用碱璃,或者我們把width設(shè)置為wrap_content弄痹,同樣會(huì)發(fā)現(xiàn)該屬性失效了,我們也會(huì)發(fā)現(xiàn)width設(shè)置為wrap_content和match_parent沒有任何的區(qū)別嵌器。
解決方法:
1肛真、針對(duì)wrap_content,只需要在onMeasure方法中指定默認(rèn)寬高即可爽航,
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode ==
MeasureSpec.AT_MOST)
setMeasuredDimension(100, 100);
else if (widthSpecMode == MeasureSpec.AT_MOST) setMeasuredDimension(100, heightSpecSize);
else if (heightSpecMode == MeasureSpec.AT_MOST) setMeasuredDimension(widthSpecSize, 100);
}
2蚓让、padding問題:在onDraw方法中對(duì)其進(jìn)行修改;
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
int width = getWidth() - paddingLeft - paddingRight;
int height = getHeight() - paddingTop - paddingBottom;
int radius = 50;
canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint);
}