Android中通過實現線程更新ProgressDialog(對話進度條),progressdialog進度條
作為開發人員我們需要經常站在使用者角度考慮問題,比如在軟體市集下載軟體時,當使用者點擊下載按鈕,則會有下載進度提示頁面出現,現在我們通過線程休眠的方式類比下載進度更新的示範,(這裡為了方便設定對話進度條位於螢幕上方):
layout介面代碼(僅部署一個按鈕):
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" android:layout_width="match_parent" 4 android:layout_height="match_parent"> 5 <Button 6 android:layout_width="wrap_content" 7 android:layout_height="wrap_content" 8 android:text="下載"//真正項目時建議將文本資源統一定義配置在res下的strings.xml中 9 android:onClick="begin"/>10 </LinearLayout>
Java代碼實現(通過線程實現類比下載進度更新):
1 public class ProgressBarDemo extends AppCompatActivity { 2 @Override 3 protected void onCreate(@Nullable Bundle savedInstanceState) { 4 super.onCreate(savedInstanceState); 5 setContentView(R.layout.progressbar); 6 } 7 public void begin(View v) { 8 //執行個體化進度條對話方塊(ProgressDialog) 9 final ProgressDialog pd = new ProgressDialog(this);10 pd.setTitle("請稍等");11 //設定對話進度條樣式為水平12 pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);13 //設定提示資訊14 pd.setMessage("正在玩命下載中......");15 //設定對話進度條顯示在螢幕頂部(方便)16 pd.getWindow().setGravity(Gravity.TOP);17 pd.setMax(100);18 pd.show();//調用show方法顯示進度條對話方塊19 //使用匿名內部類實現線程並啟動20 new Thread(new Runnable() {21 int initial = 0;//初始下載進度22 @Override23 public void run() {24 while(initial<pd.getMax()){//設定迴圈條件25 pd.setProgress(initial+=40);//設定每次完成4026 try {27 Thread.sleep(1000);28 } catch (InterruptedException e) {29 e.printStackTrace();30 }31 }32 pd.dismiss();//進度完成時對話方塊消失33 }34 }).start();35 }36 }