Create a new project, create a new DashBoardView inherited self View OnGlobalLayoutListener -implementing interface, and override the OnDraw method.
The use of OnGlobalLayoutListener interfaces requires overriding onGlobalLayout methods. In this method we will get the width of the view.
Create a new variable such as the following:
private Context mContext; private Paint mCirclePaint,mDegreePaint,mHourPaint,mMinPaint; privateint mViewWidth,mViewHeight;
Initialize these variables:
public void init (context context) {Mcontext = context;Mcirclepaint = new Paint (Paint. ANTI_alias_flag);Mdegreepaint = new Paint (Paint. ANTI_alias_flag);Mhourpaint = new Paint (Paint. ANTI_alias_flag);Mminpaint = new Paint (Paint. ANTI_alias_flag);Mcirclepaint. Setantialias(true);Mcirclepaint. Setstrokewidth(5);Mcirclepaint. SetStyle(Paint. Style. STROKE);Mhourpaint. Setstrokewidth( -);Mminpaint. Setstrokewidth(Ten);Getviewtreeobserver (). Addongloballayoutlistener(this);}
onGlobalLayoutIn the initialization of the DashBoardView wide height:
@Override publicvoidonGlobalLayout() { mViewHeight = getHeight(); mViewWidth = getWidth(); }
Add, for example, the following drawing code in the OnDraw method:
/ * * Draw dial Round * */Canvas. Drawcircle(mviewwidth/2, mviewheight/2, mviewwidth/2, Mcirclepaint); / * * Draw scale * */for (int i=0; i<24;i++) {if (i==0|| i==6|| i== A|| i== -){/ * * Draw the hourly tick * */Mdegreepaint. Setstrokewidth(5);Mdegreepaint. Settextsize( -);Canvas. DrawLine(mviewwidth/2, mviewheight/2-mviewwidth/2, mviewwidth/2, mviewheight/2-mviewwidth/2+ -, Mdegreepaint);String degree = string. ValueOf(i);Canvas. DrawText(degree,mviewwidth/2-mdegreepaint. Measuretext(degree)/2, mviewheight/2-mviewwidth/2+ -, Mdegreepaint);}else{Mdegreepaint. Setstrokewidth(3);Mdegreepaint. Settextsize( the);Canvas. DrawLine(mviewwidth/2, mviewheight/2-mviewwidth/2, mviewwidth/2, mviewheight/2-mviewwidth/2+ -, Mdegreepaint);String degree = string. ValueOf(i);Canvas. DrawText(degree,mviewwidth/2-mdegreepaint. Measuretext(degree)/2, mviewheight/2-mviewwidth/2+ -, Mdegreepaint);}/ * * To draw all the scales by rotating the canvas * */Canvas. Rotate( the, mviewwidth/2, mviewheight/2);}/ * * Draw the pointer * */Mhourpaint. Setstrokewidth( -);Mminpaint. Setstrokewidth(Ten);Canvas. Save();Canvas. Translate(mviewwidth/2, mviewheight/2);Canvas. DrawLine(0,0, -, -, Mhourpaint);Canvas. DrawLine(0,0, -, $, Mminpaint);Canvas. Restore();
So we're finished. A dashboard is drawn. For example, the following:
Full code Download: Full Project
Android's own definition of the view dashboard