「加載中」的轉圈動畫幾乎每個應用都要用,但系統自帶的 ProgressDialog 樣式老舊、可控性差。本文分享一個輕量的自定義方案:繼承 Dialog,塞進自己的布局,再用一個自定義 style 換掉那個轉圈的 drawable。整體思路清晰,代碼量也不大。
系統的 ProgressDialog 本身也是繼承 Dialog 的,所以我們照同樣的路子走:在構造函數裡 inflate 自己的布局,並調整 window 屬性。
/**
* 自定義轉圈加載對話框
*/
public class CustomProgressBarDialog extends Dialog {
private LayoutInflater inflater;
private Context mContext;
private LayoutParams lp;
public CustomProgressBarDialog(Context context) {
super(context, R.style.NoTitleDialog);
this.mContext = context;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.custom_progressbar, null);
setContentView(layout);
// 設置 window 屬性
lp = getWindow().getAttributes();
lp.gravity = Gravity.CENTER;
lp.dimAmount = 0; // 去掉背景遮罩
lp.alpha = 1.0f;
getWindow().setAttributes(lp);
}
}
兩個細節值得說明:R.style.NoTitleDialog 去掉標題欄,讓彈窗只剩內容;lp.dimAmount = 0 取消背後變暗的遮罩——加載框通常希望用戶還能看見上下文,而不是整屏被壓黑。
setContentView 傳入的 view 定義在 custom_progressbar.xml 中,一個轉圈控件加一行提示文字:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/CustomProgessBarStyle"
android:padding="10dip"
android:layout_gravity="center"
android:gravity="center" />
<TextView
android:id="@+id/load_info_text"
android:text="@string/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:padding="10dip" />
</LinearLayout>
<style name="CustomProgessBarStyle">
<item name="android:indeterminateDrawable">@drawable/custom_progress_bar</item>
<item name="android:minWidth">50dip</item>
<item name="android:maxWidth">50dip</item>
<item name="android:minHeight">50dip</item>
<item name="android:maxHeight">50dip</item>
</style>
核心就在 android:indeterminateDrawable 這一行:不確定模式的 ProgressBar 會拿這個 drawable 反覆播放,所以只要換掉它,轉起來的模樣就完全由我們自己決定。min/max 的寬高則把尺寸鎖定,避免不同 dpi 下忽大忽小。
res/drawable 支持多種類型的 drawable 資源,這裡要用的是 animation-list(逐幀動畫)或 animated-rotate(旋轉動畫)。以逐幀方式為例,把若干張切圖按順序排好、設定每幀的 android:duration,系統就會循環播放;若只有一張素材,用 animated-rotate 讓它持續旋轉同樣可行,代碼更短。
使用時只需在需要的位置 new CustomProgressBarDialog(context).show(),任務結束後調 dismiss()。建議把 dismiss() 放進 finally 或異常分支裡,別讓加載框永遠轉下去——這是自定義彈窗最常見的 bug 來源。