Android中通過實現線程更新ProgressDialog(對話進度條),progressdialog進度條

來源:互聯網
上載者:User

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 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.