如果你打算完全定製一個View,那麼你需要實現View類(所有的Android View都實現於這個類),並且實現確定尺寸的onMeasure(…))方法和確認繪圖的onDraw(…))方法。
學習Android的同學注意了!!!
學習過程中遇到什麼問題或者想獲取學習資源的話,歡迎加入Android學習交流羣,羣號碼:364595326 我們一起學Android!
如果你打算完全定製一個View,那麼你需要實現View類(所有的Android View都實現於這個類),並且實現確定尺寸的onMeasure(…))方法和確認繪圖的onDraw(…))方法。
自定義View一共分爲6步
第一步
publicclass SmileyView extendsView{
private Paint mCirclePaint;
private Paint mEyeAndMouthPaint;
privatefloatmCenterX;
privatefloatmCenterY;
privatefloatmRadius;
private RectF mArcBounds = new RectF();
publicSmileyView(Context context) {
this(context,null);
}
publicSmileyView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
publicSmileyView(Context context, AttributeSet attrs,intdefStyleAttr) {
super(context, attrs, defStyleAttr);
initPaints();
}
private void initPaints() {/* ... */}
@Override
protected void onMeasure(intwidthMeasureSpec,intheightMeasureSpec) {/* ... */}
@Override
protected void onDraw(Canvas canvas) {/* ... */}
}
2.實現畫筆paint類
本文一共兩隻畫筆
private void initPaints() {
mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCirclePaint.setStyle(Paint.Style.FILL);
mCirclePaint.setColor(Color.YELLOW);
mEyeAndMouthPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mEyeAndMouthPaint.setStyle(Paint.Style.STROKE);
mEyeAndMouthPaint.setStrokeWidth(16 * getResources().getDisplayMetrics().density);
mEyeAndMouthPaint.setStrokeCap(Paint.Cap.ROUND);
mEyeAndMouthPaint.setColor(Color.BLACK);
}
3.覆寫onMeasure(…)方法
實現這個方法告訴了母容器如何放棄自定義View,可以通過提供的measureSpecs來決定你的View的高和寬,以下是一個正方形,確認它的寬和高是一樣的。
@Override
protected void onMeasure(intwidthMeasureSpec,intheightMeasureSpec) {
intw = MeasureSpec.getSize(widthMeasureSpec);
inth = MeasureSpec.getSize(heightMeasureSpec);
intsize= Math.min(w, h);
setMeasuredDimension(size,size);
}
注意:
這個方法需要至少保證一個setMeasuredDimension(..)調用,否則會報IllegalStateException錯誤。
4.實現onSizeChanged(…)方法
這個方法是你獲取View現在的寬和高. 這裏我們計算的是中心和半徑。
@Override
protected void onSizeChanged(intw,inth,intoldw,intoldh) {
mCenterX = w / 2f;
mCenterY = h / 2f;
mRadius = Math.min(w, h) / 2f;
}
5.實現onDraw(…)方法
這個方法提供瞭如何繪製view,它提供的Canvas類可以進行繪製。
@Override
protected void onDraw(Canvas canvas) {
// draw face
canvas.drawCircle(mCenterX, mCenterY, mRadius, mCirclePaint);
// draw eyes
floateyeRadius = mRadius / 5f;
floateyeOffsetX = mRadius / 3f;
floateyeOffsetY = mRadius / 3f;
canvas.drawCircle(mCenterX - eyeOffsetX, mCenterY - eyeOffsetY, eyeRadius, mEyeAndMouthPaint);
canvas.drawCircle(mCenterX + eyeOffsetX, mCenterY - eyeOffsetY, eyeRadius, mEyeAndMouthPaint);
// draw mouth
floatmouthInset = mRadius /3f;
mArcBounds.set(mouthInset, mouthInset, mRadius * 2 - mouthInset, mRadius * 2 - mouthInset);
canvas.drawArc(mArcBounds, 45f, 90f,false, mEyeAndMouthPaint);
}
6.添加你的View
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent"/>
到此就結束了,自定義View沒你想的那麼難