Android custom (3) percentage setting of disks
I have been learning custom controls recently. Yesterday I saw someone in the Group asking how to display the disc style. I learned how to use it. So I just got started with this blog.
First, clear at a glance
You can set the display color and color block size.
Three colors are set here, which correspond to three angles of the three colors.
Code:
All of the above are custom attributes. Of course, you must assign values to custom attributes.
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();
After the attribute assignment is complete, of course, the most important part is to start drawing, that is, rewrite the onDraw () method.
@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);}
Let's continue. This is the end of the custom control definition. How can we use it? People who have read the previous blog should know it!
Please note that custom is your custom attribute. Before you declare xmlns: custom = http://schemas.android.com/apk/res/your own package name
This is almost the case. You can debug the functions you want when you cannot understand the code logic of others. This is also a good solution.