Android中使用自定義View實現下載進度的顯示


  一般有下載功能的應用都會有這樣一個場景,需要一個圖標來標識不同的狀態。之前在公司的項目中寫過一個,今天抽空來整理一下。

  一般下載都會有這么幾種狀態:未開始、等待、正在下載、下載結束,當然有時候會有下載出錯的狀態。等待狀態是指用戶點擊開始下載,但是線程池中沒有空閑的線程來處理該次下載,所以狀態為等待。

效果圖:

 

 

  這里我只是演示了一下下載和暫停的狀態,其他狀態沒有演示,在代碼中設置就可以了。

實現代碼:

1、自定義View

  1 public class DownloadPercentView extends View {
  2 
  3     public final static int STATUS_PEDDING = 1;
  4     public final static int STATUS_WAITING = 2;
  5     public final static int STATUS_DOWNLOADING = 3;
  6     public final static int STATUS_PAUSED = 4;
  7     public final static int STATUS_FINISHED = 5;
  8 
  9     // 畫實心圓的畫筆
 10     private Paint mCirclePaint;
 11     // 畫圓環的畫筆
 12     private Paint mRingPaint;
 13     // 繪制進度文字的畫筆
 14     private Paint mTxtPaint;
 15     // 圓形顏色
 16     private int mCircleColor;
 17     // 圓環顏色
 18     private int mRingColor;
 19     // 半徑
 20     private int mRadius;
 21     // 圓環寬度
 22     private int mStrokeWidth = 2;
 23     // 圓心x坐標
 24     private int mXCenter;
 25     // 圓心y坐標
 26     private int mYCenter;
 27     // 總進度
 28     private int mTotalProgress = 100;
 29     // 當前進度
 30     private int mProgress;
 31     //下載狀態
 32     private int mStatus = 1;
 33 
 34     //默認顯示的圖片
 35     private Bitmap mNotBeginImg;
 36     //暫停時中間顯示的圖片
 37     private Bitmap mPausedImg;
 38     //等待時顯示的圖片
 39     private Bitmap mWatiImg;
 40     //下載完成時顯示的圖片
 41     private Bitmap finishedImg;
 42 
 43 
 44 
 45     public DownloadPercentView(Context context, AttributeSet attrs) {
 46         super(context, attrs);
 47         // 獲取自定義的屬性
 48         initAttrs(context, attrs);
 49         initVariable();
 50     }
 51 
 52     private void initAttrs(Context context, AttributeSet attrs) {
 53         TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs,
 54                 R.styleable.DownloadPercentView, 0, 0);
 55         mRadius = (int)typeArray.getDimension(R.styleable.DownloadPercentView_radius, 100);
 56         mNotBeginImg = ((BitmapDrawable)typeArray.getDrawable(R.styleable.DownloadPercentView_notBeginImg)).getBitmap();
 57         mPausedImg = ((BitmapDrawable)typeArray.getDrawable(R.styleable.DownloadPercentView_pausedImg)).getBitmap();
 58         mWatiImg = ((BitmapDrawable)typeArray.getDrawable(R.styleable.DownloadPercentView_waitImg)).getBitmap();
 59         finishedImg = ((BitmapDrawable)typeArray.getDrawable(R.styleable.DownloadPercentView_finishedImg)).getBitmap();
 60 
 61         mNotBeginImg = big(mNotBeginImg, mRadius * 2, mRadius * 2);
 62         mPausedImg = big(mPausedImg, mRadius * 2, mRadius * 2);
 63         mWatiImg = big(mWatiImg, mRadius * 2, mRadius * 2);
 64         finishedImg = big(finishedImg, mRadius * 2, mRadius * 2);
 65 
 66         mStrokeWidth = (int)typeArray.getDimension(R.styleable.DownloadPercentView_strokeWidth, 2);
 67 
 68 //        mRadius = Math.max(mNotBeginImg.getWidth()/2, mNotBeginImg.getHeight()/2) + mStrokeWidth;
 69         mCircleColor = typeArray.getColor(R.styleable.DownloadPercentView_circleColor, 0xFFFFFFFF);
 70         mRingColor = typeArray.getColor(R.styleable.DownloadPercentView_ringColor, 0xFFFFFFFF);
 71     }
 72 
 73     private void initVariable() {
 74         //初始化繪制灰色圓的畫筆
 75         mCirclePaint = new Paint();
 76         mCirclePaint.setAntiAlias(true);
 77         mCirclePaint.setColor(mCircleColor);
 78         mCirclePaint.setStyle(Paint.Style.STROKE);
 79         mCirclePaint.setStrokeWidth(mStrokeWidth);
 80 
 81         //初始化繪制圓弧的畫筆
 82         mRingPaint = new Paint();
 83         mRingPaint.setAntiAlias(true);
 84         mRingPaint.setColor(mRingColor);
 85         mRingPaint.setStyle(Paint.Style.STROKE);
 86         mRingPaint.setStrokeWidth(mStrokeWidth);
 87 
 88         //初始化繪制文字的畫筆
 89         mTxtPaint = new Paint();
 90         mTxtPaint.setAntiAlias(true);
 91         mTxtPaint.setColor(Color.parseColor("#52ce90"));
 92         mTxtPaint.setTextAlign(Paint.Align.CENTER);
 93         mTxtPaint.setTextSize(24);
 94 
 95     }
 96 
 97     @Override
 98     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 99         int width = (int)Math.ceil(mRadius) * 2;
100         setMeasuredDimension(width, width);
101     }
102     
103     @Override
104     protected void onDraw(Canvas canvas) {
105         mXCenter = getWidth() / 2;
106         mYCenter = getHeight() / 2;
107         switch (mStatus) {
108             case STATUS_PEDDING:
109                 canvas.drawBitmap(mNotBeginImg, 0, 0, null);
110                 break;
111             case STATUS_WAITING:
112                 canvas.drawBitmap(mWatiImg, 0, 0, null);
113                 break;
114             case STATUS_DOWNLOADING:
115                 drawDownloadingView(canvas);
116                 break;
117             case STATUS_PAUSED:
118                 drawPausedView(canvas);
119                 break;
120             case STATUS_FINISHED:
121                 canvas.drawBitmap(finishedImg, 0, 0, null);
122                 break;
123         }
124 
125     }
126 
127     /**
128      * 繪制下載中的view
129      * @param canvas
130      */
131     private void drawDownloadingView(Canvas canvas) {
132         //繪制灰色圓環
133         canvas.drawCircle(mXCenter, mYCenter, mRadius - mStrokeWidth/2, mCirclePaint);
134 
135         //繪制進度扇形圓環
136         RectF oval = new RectF();
137         //設置橢圓上下左右的坐標
138         oval.left = mXCenter - mRadius + mStrokeWidth/2;
139         oval.top = mYCenter - mRadius + mStrokeWidth/2;
140         oval.right = mXCenter + mRadius - mStrokeWidth/2;
141         oval.bottom = mYCenter + mRadius - mStrokeWidth/2;
142         canvas.drawArc(oval, -90, ((float)mProgress / mTotalProgress) * 360, false, mRingPaint);
143 
144         //繪制中間百分比文字
145         String percentTxt = String.valueOf(mProgress);
146         //計算文字垂直居中的baseline
147         Paint.FontMetricsInt fontMetrics = mTxtPaint.getFontMetricsInt();
148         float baseline = oval.top + (oval.bottom - oval.top - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
149         canvas.drawText(percentTxt, mXCenter, baseline, mTxtPaint);
150 
151     }
152 
153     /**
154      * 繪制暫停時的view
155      * @param canvas
156      */
157     private void drawPausedView(Canvas canvas) {
158         //繪制灰色圓環
159         canvas.drawCircle(mXCenter, mYCenter, mRadius - mStrokeWidth/2, mCirclePaint);
160 
161         //繪制進度扇形圓環
162         RectF oval = new RectF();
163         //設置橢圓上下左右的坐標
164         oval.left = mXCenter - mRadius + mStrokeWidth/2;
165         oval.top = mYCenter - mRadius + mStrokeWidth/2;
166         oval.right = mXCenter + mRadius - mStrokeWidth/2;
167         oval.bottom = mYCenter + mRadius - mStrokeWidth/2;
168         canvas.drawArc(oval, -90, ((float) mProgress / mTotalProgress) * 360, false, mRingPaint);
169 
170         //繪制中間暫停圖標
171         canvas.drawBitmap(mPausedImg, 0, 0, null);
172     }
173 
174     /**
175      * 更新進度
176      * @param progress
177      */
178     public void setProgress(int progress) {
179         mProgress = progress;
180         postInvalidate();
181     }
182 
183     /**
184      * 設置下載狀態
185      * @param status
186      */
187     public void setStatus(int status) {
188         this.mStatus = status;
189         postInvalidate();
190     }
191 
192     /**
193      * 獲取下載狀態
194      * @return
195      */
196     public int getStatus() {
197         return mStatus;
198     }
199 
200     public static Bitmap big(Bitmap b,float x,float y)
201     {
202         int w=b.getWidth();
203         int h=b.getHeight();
204         float sx=(float)x/w;
205         float sy=(float)y/h;
206         Matrix matrix = new Matrix();
207         matrix.postScale(sx, sy); // 長和寬放大縮小的比例
208         Bitmap resizeBmp = Bitmap.createBitmap(b, 0, 0, w,
209                 h, matrix, true);
210         return resizeBmp;
211     }
212 
213 }

2、自定義屬性

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <resources>
 3 
 4     <declare-styleable name="DownloadPercentView">
 5         <attr name="radius" format="dimension"/>
 6         <attr name="notBeginImg" format="string"/>
 7         <attr name="waitImg" format="string"/>
 8         <attr name="pausedImg" format="string"/>
 9         <attr name="finishedImg" format="string"/>
10         <attr name="strokeWidth" format="dimension"/>
11         <attr name="circleColor" format="color"/>
12         <attr name="ringColor" format="color"/>
13     </declare-styleable>
14     
15 </resources>

3、使用自定義布局

  首先在布局文件中引用:

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:custom="http://schemas.android.com/apk/res-auto"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
 6     android:paddingRight="@dimen/activity_horizontal_margin"
 7     android:paddingTop="@dimen/activity_vertical_margin"
 8     android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
 9 
10     <com.bbk.lling.downloadpercentdemo.DownloadPercentView
11         android:id="@+id/downloadView"
12         android:layout_width="wrap_content"
13         android:layout_height="wrap_content"
14         android:layout_centerInParent="true"
15         custom:notBeginImg="@drawable/ic_no_download"
16         custom:waitImg="@drawable/ic_wait"
17         custom:pausedImg="@drawable/ic_pause"
18         custom:finishedImg="@drawable/ic_finished"
19         custom:strokeWidth="2dp"
20         custom:circleColor="#bdbdbd"
21         custom:radius="18dp"
22         custom:ringColor="#52ce90"/>
23 
24 </RelativeLayout>

 

  然后我這里在Activity使用一個線程來模擬下載過程來演示:

 1 package com.bbk.lling.downloadpercentdemo;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.os.Handler;
 6 import android.os.Message;
 7 import android.view.View;
 8 
 9 
10 public class MainActivity extends Activity {
11 
12     public final static int MSG_UPDATE = 1;
13     public final static int MSG_FINISHED = 2;
14 
15     private DownloadPercentView mDownloadPercentView;
16     private int mDownloadProgress = 0;
17     private Handler mHandler = new InnerHandler();
18     private boolean downloading = false;
19 
20     @Override
21     protected void onCreate(Bundle savedInstanceState) {
22         super.onCreate(savedInstanceState);
23         setContentView(R.layout.activity_main);
24         mDownloadPercentView = (DownloadPercentView) findViewById(R.id.downloadView);
25         mDownloadPercentView.setOnClickListener(new View.OnClickListener() {
26             @Override
27             public void onClick(View v) {
28                 if(mDownloadPercentView.getStatus() == DownloadPercentView.STATUS_PEDDING
29                         || mDownloadPercentView.getStatus() == DownloadPercentView.STATUS_PAUSED) {
30                     downloading = true;
31                     mDownloadPercentView.setStatus(DownloadPercentView.STATUS_DOWNLOADING);
32                     //模擬下載
33                     new Thread(new Runnable() {
34                         @Override
35                         public void run() {
36                             while (downloading) {
37                                 if(mDownloadProgress == 100) {
38                                     mHandler.sendEmptyMessage(MSG_FINISHED);
39                                     return;
40                                 }
41                                 mDownloadProgress += 1;
42                                 mHandler.sendEmptyMessage(MSG_UPDATE);
43                                 try{
44                                     Thread.sleep(100);
45                                 } catch (Exception e) {
46                                 }
47 
48                             }
49                         }
50                     }).start();
51                 } else if(mDownloadPercentView.getStatus() == DownloadPercentView.STATUS_DOWNLOADING){
52                     downloading = false;
53                     mDownloadPercentView.setStatus(DownloadPercentView.STATUS_PAUSED);
54                 }
55             }
56         });
57     }
58 
59     class InnerHandler extends Handler {
60         @Override
61         public void handleMessage(Message msg) {
62             switch (msg.what) {
63                 case MSG_FINISHED:
64                     mDownloadPercentView.setStatus(DownloadPercentView.STATUS_FINISHED);
65                     break;
66                 case MSG_UPDATE:
67                     mDownloadPercentView.setProgress(mDownloadProgress);
68                     break;
69             }
70             super.handleMessage(msg);
71         }
72     }
73 
74 
75 }

 

源碼下載:https://github.com/liuling07/DownloadPercentDemo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM