效果图:
0.为了圆形进度条的扩展性,将部分属性定义在attrs.xml中,有利于定制化
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CircleProgressBar">
<!--圆环相关-->
<attr name="roundWidth" format="dimension" />
<attr name="roundColor" format="color" />
<!--进度相关-->
<attr name="progressColor" format="color" />
<attr name="curProgress" format="integer" />
<attr name="maxProgress" format="integer" />
<!--百分比文本-->
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
1.CircleProgressBar.java
package com.xing.circleprogressbar;
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.graphics.Typeface;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
/**
* Created by Administrator on 2016/4/22.
*/
public class CircleProgressBar extends View {
private Paint paint;
private int mWidth; //控件的宽度,宽和高相等
private int roundWidth; //圆环的宽度
private int roundColor; //圆环的颜色
private int progressColor; //进度条的颜色
private int curProgress; //进度条当前的进度,根据这个进度计算要偏移的多少角度
private int maxProgress = 100; //进度条最大的进度。
private int textSize; //百分比的字体大小
private int textColor; //百分比的字体的颜色
public CircleProgressBar(Context context) {
this(context, null);
}
public CircleProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attrs) {
paint = new Paint();
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CircleProgressBar);
//将圆环的宽度设置为16dp,转换为像素,适应平台
roundWidth = (int) (typedArray.getDimension(R.styleable.CircleProgressBar_roundWidth, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics())));
roundColor = typedArray.getColor(R.styleable.CircleProgressBar_roundColor, Color.parseColor("#11339ED4"));
progressColor = typedArray.getColor(R.styleable.CircleProgressBar_progressColor, Color.parseColor("#3F51B5"));
curProgress = typedArray.getInt(R.styleable.CircleProgressBar_curProgress, 0);
maxProgress = typedArray.getInt(R.styleable.CircleProgressBar_maxProgress, 100);
textSize = (int) typedArray.getDimension(R.styleable.CircleProgressBar_textSize, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()));
textColor = typedArray.getColor(R.styleable.CircleProgressBar_textColor, Color.BLACK);
typedArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//设置圆心坐标,为控件的宽度的一半
int centerX = mWidth / 2;
int centerY = centerX;
//设置半径
int radius = centerX - roundWidth / 2;
//设置画笔颜色
paint.setColor(roundColor);
//设置画笔为空心
paint.setStyle(Paint.Style.STROKE);
//设置抗锯齿
paint.setAntiAlias(true);
//设置圆环的宽度
paint.setStrokeWidth(roundWidth);
//绘制圆形
canvas.drawCircle(centerX, centerY, radius, paint);
//绘制圆环进度
paint.setColor(progressColor);
RectF rectF = new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius);
float endDegree = 360 * (float) curProgress / (float) maxProgress;
//起始角度为最上顶点,
/**
* drawArc(RectF rectF,int startAngle,int sweepAngle,boolean useCenter,Paint paint)
* 第一个参数:指定圆弧的外轮廓矩形区域
* 第二个参数;圆弧的起始角度,单位为度
* 第三个参数:圆弧扫过的角度,顺时针方向,单位为度,从右中间开始为零度,绘制一圈,即要360度,
* 第四个参数:true表示绘制圆弧将圆心包括在内,通常用来绘制扇形
*
* */
canvas.drawArc(rectF, -90, endDegree, false, paint);
/**绘制文本信息*/
paint.setStrokeWidth(0);
//设置百分比字体颜色
paint.setColor(textColor);
//设置百分比字体为粗体
paint.setTypeface(Typeface.DEFAULT_BOLD);
//设置百分比字体大小
paint.setTextSize(textSize);
//得到文本的总宽度
float textWidth;
String result = "";
if (curProgress == 100) {
result = "Done";
textWidth = paint.measureText(result);
} else {
result = curProgress + "%";
textWidth = paint.measureText(result);
}
canvas.drawText(result, centerX - textWidth / 2, centerY + textSize / 2, paint);
}
/***
* 在onMeasure中,如果MeasurecSpec的模式是AT_MOST则把宽高设置为80dp,否则,在布局文件中将宽高设置wrap_content,将是和父控件一样大
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
if (widthMode == MeasureSpec.AT_MOST) {
mWidth = Math.min(widthSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics()));
setMeasuredDimension(mWidth, mWidth);
} else {
mWidth = getWidth();
}
}
public void setRoundWidth(int roundWidth) {
this.roundWidth = roundWidth;
}
public void setRoundColor(int roundColor) {
this.roundColor = roundColor;
}
public void setProgressColor(int progressColor) {
this.progressColor = progressColor;
}
public void setCurProgress(int curProgress) {
if (curProgress < 0) {
this.curProgress = 0;
} else {
this.curProgress = curProgress;
}
invalidate(); //重绘组件
}
public void setMaxProgress(int maxProgress) {
this.maxProgress = maxProgress;
}
public void setTextSize(int textSize) {
this.textSize = textSize;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
}
}
2.将圆形进度条用于ProgressDialog中,以下是自定义的ProgressDialog
自定义ProgressDialog的布局文件
layout_progress_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/dialog_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/dialog_background"
android:gravity="center_horizontal"
android:orientation="vertical">
<com.xing.circleprogressbar.CircleProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
app:curProgress="0"
app:maxProgress="100"
app:progressColor="#ffffff"
app:roundWidth="3dp"
app:textColor="#ffffff"
app:textSize="20sp" />
</LinearLayout>
其中background为:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#aa000000" />
</shape>
ProgressBarDialog.java
package com.xing.circleprogressbar;
import android.app.Dialog;
import android.content.Context;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
/**
* Created by Administrator on 2016/4/22.
*/
public class ProgressBarDialog extends Dialog {
private static ProgressBarDialog dialog;
public ProgressBarDialog(Context context) {
this(context, R.style.CustomProgressDialogStyle);
}
public ProgressBarDialog(Context context, int theme) {
super(context, theme);
}
public static ProgressBarDialog createDialog(Context context) {
dialog = new ProgressBarDialog(context);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(false);
View view = View.inflate(context, R.layout.layout_progress_dialog, null);
LinearLayout layout = (LinearLayout) view.findViewById(R.id.dialog_layout);
dialog.setContentView(layout, new LinearLayout.LayoutParams(
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, context.getResources().getDisplayMetrics()),
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160, context.getResources().getDisplayMetrics())));
return dialog;
}
}
ProgressDialog样式
<style name="CustomProgressDialogStyle" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsTranslucent">true</item>
</style>
测试代码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="下载" />
</LinearLayout>
MainActivity.java
package com.xing.circleprogressbar;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private String path = "http://10.0.3.2:8080/video.avi"; //genymotion模拟器url
private CircleProgressBar progressBar;
private ProgressBarDialog dialog;
int contentLength;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
dialog = ProgressBarDialog.createDialog(this);
if (dialog != null) {
dialog.show();
}
new DownloadTask().execute(path);
}
class DownloadTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = (CircleProgressBar) dialog.findViewById(R.id.progressBar);
progressBar.setCurProgress(0);
}
@Override
protected String doInBackground(String... str) {
String path = str[0];
HttpURLConnection conn = null;
FileOutputStream fos = null;
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
contentLength = conn.getContentLength();
InputStream is = conn.getInputStream();
Map<String, List<String>> map = conn.getHeaderFields();
for (String key : map.keySet()) {
List<String> list = map.get(key);
for (String s : list) {
System.out.println("key:" + key + " ,value:" + new String(s.getBytes("ISO-8859-1"), "GBK"));
}
}
int count = 0;
byte[] buffer = new byte[1024 * 4];
if (!isSdcardAvaiable()) {
return "sdcard failed";
}
File destFile = new File(getsdcardDir(), "wwww.avi");
fos = new FileOutputStream(destFile);
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
count = count + len;
publishProgress((int) (count * 100.0f / contentLength));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "success";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setCurProgress(values[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
}
}
private boolean isSdcardAvaiable() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
private String getsdcardDir() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
}