# Android 中怎么使用ProgressDialog實現進度條
## 目錄
1. [ProgressDialog概述](#1-progressdialog概述)
2. [基本用法](#2-基本用法)
2.1 [創建ProgressDialog](#21-創建progressdialog)
2.2 [設置樣式與屬性](#22-設置樣式與屬性)
3. [進度條類型詳解](#3-進度條類型詳解)
3.1 [不確定進度條](#31-不確定進度條)
3.2 [確定進度條](#32-確定進度條)
4. [自定義ProgressDialog](#4-自定義progressdialog)
4.1 [自定義布局](#41-自定義布局)
4.2 [樣式主題修改](#42-樣式主題修改)
5. [線程與異步處理](#5-線程與異步處理)
5.1 [Handler實現](#51-handler實現)
5.2 [AsyncTask實現](#52-asynctask實現)
6. [替代方案與最佳實踐](#6-替代方案與最佳實踐)
6.1 [ProgressBar替代方案](#61-progressbar替代方案)
6.2 [Material Design組件](#62-material-design組件)
7. [常見問題與解決方案](#7-常見問題與解決方案)
8. [完整代碼示例](#8-完整代碼示例)
---
## 1. ProgressDialog概述
ProgressDialog是Android提供的一個模態對話框,用于在后臺任務執行時向用戶顯示進度反饋。雖然Google官方已建議使用`ProgressBar`或`AlertDialog`替代(API 26+),但在兼容舊版本時仍具實用價值。
**核心特性**:
- 支持不確定進度(旋轉圓圈)
- 支持確定進度(水平進度條)
- 可自定義標題、消息和圖標
---
## 2. 基本用法
### 2.1 創建ProgressDialog
```java
// 基礎創建示例
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("加載中...");
progressDialog.setCancelable(false); // 禁止點擊外部取消
progressDialog.show();
| 方法 | 作用 |
|---|---|
setTitle() |
設置對話框標題 |
setMessage() |
設置提示文本 |
setProgressStyle() |
設置進度條樣式(STYLE_SPINNER/STYLE_HORIZONTAL) |
setMax() |
設置最大進度值(僅確定進度有效) |
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // 默認樣式
dialog.setMessage("正在處理...");
dialog.show();
// 3秒后自動關閉
new Handler().postDelayed(() -> dialog.dismiss(), 3000);
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.setProgress(0);
// 模擬進度更新
new Thread(() -> {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(50);
dialog.setProgress(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dialog.dismiss();
}).start();
custom_progress.xml:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Large"/>
<TextView
android:id="@+id/tv_custom"
android:text="自定義文本"/>
</LinearLayout>
ProgressDialog dialog = new ProgressDialog(context);
View view = LayoutInflater.from(context).inflate(R.layout.custom_progress, null);
dialog.setView(view);
((TextView)view.findViewById(R.id.tv_custom)).setText("處理中...");
在styles.xml中定義:
<style name="MyProgressDialog" parent="Theme.AppCompat.Dialog">
<item name="colorAccent">@color/red</item>
<item name="android:textColorPrimary">#000000</item>
</style>
應用主題:
ProgressDialog dialog = new ProgressDialog(new ContextThemeWrapper(context, R.style.MyProgressDialog));
Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
progressDialog.setProgress(msg.arg1);
}
}
};
new Thread(() -> {
for (int i = 0; i <= 100; i++) {
Message msg = handler.obtainMessage(1);
msg.arg1 = i;
handler.sendMessage(msg);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
private class MyTask extends AsyncTask<Void, Integer, Void> {
private ProgressDialog pd;
@Override
protected void onPreExecute() {
pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.show();
}
@Override
protected Void doInBackground(Void... voids) {
for (int i = 0; i <= 100; i++) {
publishProgress(i);
SystemClock.sleep(50);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
pd.setProgress(values[0]);
}
@Override
protected void onPostExecute(Void aVoid) {
pd.dismiss();
}
}
<!-- 布局文件中直接使用 -->
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"/>
使用MaterialAlertDialogBuilder(需Material組件庫):
new MaterialAlertDialogBuilder(context)
.setView(R.layout.progress_layout)
.setTitle("處理中")
.setCancelable(false)
.show();
| 問題 | 解決方案 |
|---|---|
| 內存泄漏 | 使用WeakReference包裹Context |
| 主線程阻塞 | 確保進度更新在UI線程執行 |
| 樣式不統一 | 應用AppCompat主題 |
| 廢棄警告 | 使用AlertDialog+ProgressBar組合 |
// 完整Activity示例
public class MainActivity extends AppCompatActivity {
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnShow = findViewById(R.id.btn_show);
btnShow.setOnClickListener(v -> showProgressDialog());
}
private void showProgressDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("文件下載");
progressDialog.setMessage("請稍候...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.show();
new Thread(this::mockDownload).start();
}
private void mockDownload() {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(100);
runOnUiThread(() -> progressDialog.setProgress(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
progressDialog.dismiss();
}
}
注意:實際開發中建議結合ViewModel和LiveData實現更優雅的架構設計。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。