Android自訂(三)實現圓盤的百分比設定
最近一直在學習自訂控制項,昨天看到群裡有人問如何如何?圓盤樣式的顯示,學有所用,於是乎就有了這篇部落格
先,一目瞭然
這裡的顯示顏色以及顏色塊的大小你都可以自己設定
這裡設定了三種顏色,對應三種顏色的三個角度
上代碼:
以上都屬於自訂屬性,當然自訂了屬性就要給它賦值
TypedArray mArray = context.obtainStyledAttributes(attrs,R.styleable.CustomCircle, defStyleAttr, 0);firstColor = mArray.getColor(R.styleable.CustomCircle_firstColor,Color.BLUE);secondColor = mArray.getColor(R.styleable.CustomCircle_secondColor,Color.GREEN);thirdColor = mArray.getColor(R.styleable.CustomCircle_thirdColor,Color.RED);firstAngle=mArray.getInt(R.styleable.CustomCircle_firstAngle, 90);secondAngle=mArray.getInt(R.styleable.CustomCircle_secondAngle, 180);thirdAngle=mArray.getInt(R.styleable.CustomCircle_thirdAngle, 120);mArray.recycle();
屬性賦值結束後,當然就要開始最重要的部分了,畫圖,也就是重寫onDraw()方法
@Overrideprotected void onDraw(Canvas canvas) {int center=getWidth()/2;int radius=center/2;mPaint.setColor(Color.GRAY);mPaint.setStrokeWidth(center);mPaint.setAntiAlias(true);mPaint.setStyle(Paint.Style.STROKE);canvas.drawCircle(center, center, radius, mPaint);mPaint.setColor(firstColor);RectF rectF=new RectF(center-radius, center-radius, center+radius, center+radius);canvas.drawArc(rectF, 0, firstAngle, false, mPaint);mPaint.setColor(secondColor);canvas.drawArc(rectF, firstAngle, secondAngle, false, mPaint);mPaint.setColor(thirdColor);canvas.drawArc(rectF, secondAngle, thirdAngle, false, mPaint);}
我們繼續,自訂控制項就這麼定義結束了,如何用呢?看過前面部落格的人們應該知道吧!
這裡需要注意的是custom,這就是你自訂的屬性了,前面要聲明一下xmlns:custom=http://schemas.android.com/apk/res/你自己的包名
差不多就這樣啦,就實現了你想要的功能,當你看不懂別人的代碼邏輯時,你可以debug,這也是一個很好地辦法