1. 程式人生 > >android_studio的自定義View的圓形進度條

android_studio的自定義View的圓形進度條

**需要 考試第三方**
**MyView寫法如下**
package com.bawei.lss_yuan;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view
.View; import java.util.Timer; import java.util.TimerTask; public class MyView extends View{ private float cx; private float cy; private float radius; private Paint paint; private int sweepAngle; private int color; public MyView(Context context) { super(context);
} public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); //獲取自定義屬性 TypedArray a=context.obtainStyledAttributes(attrs,R.styleable
.MyView); //獲取顏色,圓的顏色 color=a.getColor(R.styleable.MyView_circle_color, Color.BLACK); //圓的半徑 radius=a.getDimension(R.styleable.MyView_circle_radius,100); //圓的距離 cx=a.getDimension(R.styleable.MyView_circle_x,260); cy=a.getDimension(R.styleable.MyView_circle_y,260); a.recycle(); paint=new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { if(sweepAngle>360){ return; } sweepAngle+=1; postInvalidate(); } },1000,20); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setColor(color); paint.setStrokeWidth(5); canvas.drawCircle(cx,cy,radius,paint); //進度條走動顏色 paint.setColor(Color.RED); RectF rectF=new RectF(cx - radius, cy - radius, cx + radius, cy + radius); canvas.drawArc(rectF, -90, sweepAngle, false, paint); int progress= (int) (sweepAngle/360f*100); paint.setStrokeWidth(0); //百分數顏色 paint.setColor(Color.BLACK); paint.setTextSize(15); canvas.drawText(progress+"%",cx-5,cy,paint); } } **activity_main寫法如下** <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <com.bawei.lss_yuan.MyView android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> **複製values,attrs.xml的寫法如下** <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView"> <attr name="circle_color" format="color"></attr> <attr name="circle_radius" format="dimension"></attr> <attr name="circle_x" format="dimension"></attr> <attr name="circle_y" format="dimension"></attr> </declare-styleable> </resources>