Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中用線程更新 ProgressDialog 進度條

編輯:關於 Android 開發

Android 中用線程更新 ProgressDialog 進度條


作為開發者,我們需要經常站在用戶角度思考問題。比如在應用商城下載軟件時,用戶點擊下載後會出現下載進度提示頁面。下面我們通過線程休眠的方式模擬下載進度更新(為方便截圖,這裡把進度條對話框設置在屏幕上方):

layout 界面代碼(僅佈置一個按鈕):

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下載" android:onClick="begin"/> </LinearLayout>

Java 代碼實現(通過線程模擬下載進度更新):

public class ProgressBarDemo extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.progressbar); } public void begin(View v) { final ProgressDialog pd = new ProgressDialog(this); pd.setTitle("請稍等"); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setMessage("正在玩命下載中......"); pd.getWindow().setGravity(Gravity.TOP); pd.setMax(100); pd.show(); new Thread(new Runnable() { int initial = 0; @Override public void run() { while(initial<pd.getMax()){ pd.setProgress(initial+=40); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } pd.dismiss(); } }).start(); } }

關鍵點在於:先構建並配置水平樣式的 ProgressDialog,然後在一個後台線程裡循環更新進度(這裡每次遞增 40 並 sleep 一秒模擬耗時下載),當進度達到最大值時調用 dismiss() 關閉對話框。

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