Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

動手做一個漂亮的圓形載入對話框:CircleProgressDialog 完整解析

編輯:Android 資訊

本文由碼農網 – 蘇耀東原創,轉載請留意文末的轉載要求,歡迎參與我們的付費投稿計劃!

這個庫能做什麼

等待提示是 App 裡最常見也最容易被忽略的細節。CircleProgressDialog 把「圓環動畫」與「等待對話框」打包成一個可直接引入的開源庫,核心能力有兩塊:

  • 一個可獨立使用的圓形進度控制項,直接寫進佈局檔即可,圓環寬度、顏色、陰影偏移都能自訂;
  • 一個封裝好的等待 Dialog,一行程式碼彈出,同時開放 API 讓你調整配色、文案,甚至在等待過程中動態改寫提示文字。

讀完這篇,你不只會用這個庫,還能順帶掌握自訂 View 與自訂 Dialog 的通用套路。專案已放在 GitHub 上,覺得不錯的話幫忙點個 star。

先看效果

使用方式分成兩種。

方式一:寫在佈局檔裡

透過 loading_color、loading_width、shadow_offset 三個自訂屬性控制外觀。

<com.syd.oden.circleprogressdialog.view.RotateLoading oden:loading_color="@color/colorAccent" oden:loading_width="6dp" oden:shadow_offset="8dp" android:layout_width="100dp" android:layout_height="100dp" />

方式二:以對話框形式彈出

什麼都不設定時,三行就搞定:

CircleProgressDialog circleProgressDialog; circleProgressDialog = new CircleProgressDialog(this); circleProgressDialog.showDialog();

需要更細的控制也沒問題,尺寸、進度條顏色與粗細、文字顏色與內容都能改,而且可以在等待过程中依程式狀態即時更新文案與顏色:

CircleProgressDialog circleProgressDialog; circleProgressDialog = new CircleProgressDialog(this); //可對對話框的大小、進度條的顏色、寬度、文字的顏色、內容等屬性進行設置 circleProgressDialog.setDialogSize(15); circleProgressDialog.setProgressColor(Color.parseColor("#FFFFFF")); circleProgressDialog.setTextColor(Color.parseColor("#FFFFFF")); ... circleProgressDialog.showDialog(); //顯示對話框 //顯示過程中可根據狀態改變文字內容及顏色 circleProgressDialog.changeText("erro:..."); circleProgressDialog.changeTextColor(Color.parseColor("##EB0000")); circleProgressDialog.dismiss();//關閉對話框

引入依賴

先在專案的 build.gradle 中加入 JitPack 倉庫:

allprojects { repositories { ... maven { url "https://jitpack.io" } } }

再於 module 的 build.gradle 宣告依賴:

dependencies { compile 'com.github.autume:CircleProgressDialog:1.0.0' }

圓環是怎麼畫出來的

兩個必須先懂的 API

drawArc 是整個動畫的基礎:

drawArc (RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)

  • oval 是 RectF 物件,用來描述弧線所依附的橢圓範圍;
  • startAngle 是起始角度,以時鐘三點方向為 0 度;傳入值若小於 0 或大於等於 360,會先對 360 取餘數;
  • sweepAngle 是從起點沿順時針掃過的角度,大於等於 360 會畫出完整圓環,小於 0 同樣先取餘數;
  • useCenter 為 true 時,會用圓心把弧線的起點與終點連起來閉合;為 false 則直接連接兩端,不經過圓心。

RectF 則用四個數字框出一塊矩形區域:

RectF rectF = new RectF(100, 100, 300, 300);

參數依序是 left、top、right、bottom,也就是左上角與右下角的座標。圓環要畫在哪、畫多大,全看這四個值。

宣告自訂屬性

先在 attrs 資源中定義 color、dimension、boolean 等位型(format 常見取值有 string、color、dimension、integer、enum、reference、float、boolean、fraction、flag):

<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="RotateLoading"> <attr name="loading_width" format="dimension"/> <attr name="loading_color" format="color"/> <attr name="shadow_offset" format="dimension"/> <attr name="loading_visible" format="boolean"/> </declare-styleable> </resources>

RotateLoading:預設值與屬性讀取

先給出各項預設值,並準備好畫筆與兩塊矩形區域,以及控制動畫相位的一對起始角度:

private final int DEFAULT_COLOR = Color.WHITE; //默認顏色 private final int DEFAULT_WIDTH = 6; private final int DEFAULT_SHADOW_POSITION = 2; private final boolean DEFAULT_VISIBLE = true; private int color = DEFAULT_COLOR; private int width = dpToPx(DEFAULT_WIDTH); private int shadowOffset = dpToPx(DEFAULT_SHADOW_POSITION); private boolean isStart = DEFAULT_VISIBLE; private Paint mPaint = new Paint(); private RectF loadingRectF; private RectF shadowRectF; //對稱的兩個弧形起始角度 private int topDegree = 10; private int bottomDegree = 190;

接著用 TypedArray 把 XML 上寫的屬性取出來,用完記得 recycle:

private void obtainStyleAttrs(AttributeSet attrs) { TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.RotateLoading); color = typedArray.getColor(R.styleable.RotateLoading_loading_color, color); width = (int) typedArray.getDimension(R.styleable.RotateLoading_loading_width, width); shadowOffset = (int) typedArray.getDimension(R.styleable.RotateLoading_shadow_offset, shadowOffset); isStart = typedArray.getBoolean(R.styleable.RotateLoading_loading_visible, isStart); typedArray.recycle(); }

畫筆設定

要畫出圓頭線帽的空心弧線,關鍵是 STROKE 樣式加上 ROUND 線帽:

private void initView() { mPaint.setColor(color); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(width); mPaint.setStrokeCap(Paint.Cap.ROUND); }

尺寸變化時重算繪製區域

在 onSizeChanged 中才能拿到真正的寬高,這裡預留 2 倍線寬作為邊距,陰影矩形則再往右下偏移 shadowOffset:

@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); arc = 10; //占滿界面 邊距為2*width loadingRectF = new RectF(2 * width, 2 * width, w - 2 * width, h - 2 * width); shadowRectF = new RectF(2 * width + shadowOffset, 2 * width + shadowOffset, w - 2 * width + shadowOffset, h - 2 * width + shadowOffset); }

onDraw:兩段弧線的呼吸動畫

做法是畫兩段對稱的短弧(上方與下方各一),讓它們繞圓心旋轉,同時讓弧長在 10 度到 160 度之間來回伸縮,形成「呼吸」感。陰影先以半透明黑畫一次,再疊上實際顏色:

@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!isStart) { return; } mPaint.setColor(Color.parseColor("#1a000000")); canvas.drawArc(shadowRectF, topDegree, arc, false, mPaint); canvas.drawArc(shadowRectF, bottomDegree, arc, false, mPaint); mPaint.setColor(color); canvas.drawArc(loadingRectF, topDegree, arc, false, mPaint); canvas.drawArc(loadingRectF, bottomDegree, arc, false, mPaint); try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } topDegree += 10; bottomDegree += 10; if (topDegree > 360) { topDegree = topDegree - 360; } if (bottomDegree > 360) { bottomDegree = bottomDegree - 360; } if (changeBigger) { if (arc < 160) { arc += 2.5; invalidate(); } } else { if (arc > 10) { arc -= 5; invalidate(); } } if (arc == 160 || arc == 10) { changeBigger = !changeBigger; invalidate(); } }

到這裡,圓形進度條本身就算完成了,完整程式碼可直接到 GitHub 上翻。

再把它包成對話框

佈局檔

把剛剛的 RotateLoading 放進去,底下再擺一行提示文字,最外層背景設為全透明,這樣才能做出懸浮在畫面上的效果:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:oden="https://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#00000000" android:gravity="center"> <LinearLayout android:id="@+id/llProgress" android:layout_width="100dp" android:layout_height="100dp"> <com.syd.oden.circleprogressdialog.view.RotateLoading android:id="@+id/rotateloading" oden:loading_visible="false" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <TextView android:id="@+id/progreeTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:textColor="#c0000000" android:text="loading..." /> </LinearLayout>

封裝類別的欄位設計

把對外可調的項目都拉成成員變數,並給一組合理預設值:

public class CircleProgressDialog { private Context mContext; private Dialog mDialog; //默認參數 private int dialogSize = 65; private int progressColor = Color.WHITE; private int progressWidth = 6; private int shadowOffset = 2; private int textColor = Color.parseColor("#c0000000"); private String text = "loading..."; private TextView progressTextView; private boolean isShowing = false; ... }

初始化:把 dp 換成像素,並去掉系統視窗底色

設定值多半以 dp 思考,建立時透過 displayMetrics 的 density 換算,同時把 Dialog 背景設為透明,避免出現多餘的白底:

public CircleProgressDialog(Context context) { this.mContext = context; init(); } private void init() { //dialog的大小,轉化成dp float scale = mContext.getResources().getDisplayMetrics().density; dialogSize = (int) (dialogSize * scale + 0.5f); mDialog = new AlertDialog.Builder(mContext).create(); mDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); }

顯示:把設定值灌進控制項

 public void showDialog() { mDialog.show(); mDialog.setContentView(R.layout.dialog_circle_progress); //獲取控件 progressTextView = (TextView) mDialog.findViewById(R.id.progreeTextView); RotateLoading mRotateLoading = (RotateLoading) mDialog.findViewById(R.id.rotateloading); LinearLayout layout = (LinearLayout) mDialog.findViewById(R.id.llProgress); //配置相關屬性 layout.setLayoutParams(new LinearLayout.LayoutParams(dialogSize, dialogSize)); mRotateLoading.setWidth(progressWidth); mRotateLoading.setColor(progressColor); mRotateLoading.setShadowOffset(shadowOffset); progressTextView.setTextColor(textColor); progressTextView.setText(text); mRotateLoading.start(); isShowing = true; }

對外開放的 API

除了各屬性的 setter,特別保留了兩個能在動畫進行中即時修改文字的方法,這在「上傳中 → 失敗 → 重試」這類流程裡很實用:

public void changeText(String str) { if (progressTextView != null) { progressTextView.setText(str); } } public void changeTextColor(int color) { if (progressTextView != null) { progressTextView.setTextColor(color); } } ... public void setCancelable(boolean isCancelable) { if (mDialog != null) { mDialog.setCancelable(isCancelable); } } ...

至此,自訂 Dialog 也完成了。

小結

整件事拆開來看並不神秘:自訂 View 負責畫,自訂 Dialog 負責殼,中間用一組屬性把兩者串起來。掌握 drawArc、RectF 與 declare-styleable 這三件事,你就能改造出屬於自己的等待動畫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved