標籤:length dimen htm something line div ext strong nal
顯示運行進度對話方塊
我們經常有這種經曆:運行某一應用程式時。須要等待一會,這時會顯示一個進度(Please Wait)對話方塊,讓使用者知道操作進行中。
我們繼續在上一篇中的程式中加入代碼~
1、在上一篇的activity_main.xml檔案裡加入一個Button,加入後的代碼例如以下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/btn_dialog" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClick" android:text="Click to display a dialog" /> <Button android:id="@+id/btn_dialog2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClick2" android:text="Click to display a progress dialog" /></LinearLayout>
2、在MainActivity.java中加入一個onClick2()方法。加入的代碼塊例如以下:
public void onClick2(View v) {// ---show the dialog---final ProgressDialog dialog = ProgressDialog.show(this,"Doing something", "Please wait...", true);//建立一個進度對話方塊new Thread(new Runnable() {//使用Runnable代碼塊建立了一個Thread線程@Overridepublic void run() {//run()方法中的代碼將在一個單獨的線程中運行// TODO Auto-generated method stubtry {// ---simulate doing something lengthy---Thread.sleep(5000);//類比一個耗時5秒的操作// ---dismiss the dialog---dialog.dismiss();//5秒鐘後,調用dismiss方法關閉進度對話方塊} catch (InterruptedException e) {// TODO: handle exceptione.printStackTrace();}}}).start();}
3、運行。點擊第二個button。效果例如以下:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemVuYWlsNTAxMTI5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" />
5秒後,進度條自己主動消失,程式恢複原來的狀態~
點擊下載完整代碼~
Android學習筆記(八)——顯示運行進度對話方塊