繼承自View的自定義控制元件的warp_content和padding屬性處理
阿新 • • 發佈:2019-01-05
繼承自view的自定義控制元件的wrap_content和padding兩個屬性不會生效,解決方法
/** * 自定義一個圓形 * @author luoshen * 2016年11月29日下午1:28:04 */ public class CircleView extends View{ private int mColor = Color.RED; private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); public CircleView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public CircleView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CircleView(Context context) { super(context); init(); } private void init(){ mPaint.setColor(mColor); } /** * 此方法中的程式碼是為了讓wrap_content屬性生效,並給此屬性設定寬高 */ @Override 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 && heightMeasureSpec == MeasureSpec.AT_MOST) { //設定wrap_content屬性的寬高 setMeasuredDimension(200, 200); }else if (widthSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(200, heightSpecSize); }else if (heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(widthSpecSize, 200); } } /** * 此方法內部的程式碼是為了讓padding屬性生效 * * 並且畫了一個圓 */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); //減去padding值 int width = getWidth() - paddingLeft - paddingRight; int height = getHeight() - paddingBottom - paddingTop; int radius = Math.min(width,height)/2; canvas.drawCircle(paddingLeft+width/2, paddingTop+height/2, radius, mPaint); } }