不論 PC 軟體還是手機 App,我們都見過「加載中...」這類提示方塊。要在 Android 裡做出同樣的效果,就得請出 ProgressDialog。
ProgressDialog 繼承自 AlertDialog,同樣放在 android.app 套件中。它提供兩種形式,透過下面的常數切換:
選水平進度條時,進度值範圍是 0—10000。
建構子有兩個:
更常用的是它提供的靜態 show 方法,一行就能彈出對話框:
第一個參數必須是當前運行的 Activity 的 Context,傳錯會直接讓程式崩潰。
其一,後台工作結束前一定要呼叫 dismiss() 關閉對話框,否則程式可能陷入無法收尾的循環。其二,子執行緒中不得直接改動 Context 或 parent View 的狀態、文字輸出,因為執行緒裡拿到的 Context 與 View 並不屬於 parent,兩者之間沒有關聯;需要更新 UI 時應透過 Handler 或 runOnUiThread 回到主執行緒。
public class MainActivity extends Activity
{
private Button button=null;
public ProgressDialog dialog=null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.button=(Button)super.findViewById(R.id.button);
this.button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
final CharSequence strDialogTitle=MainActivity.this.getString(R.string.str_dialog_title);
final CharSequence strDialogBody=MainActivity.this.getString(R.string.str_dialog_body);
// 顯示 Progress 對話框
dialog=ProgressDialog.show(MainActivity.this,strDialogTitle,strDialogBody,true);
new Thread()
{
@Override
public void run()
{
try
{
// 表示後台運行的代碼段,以暫停 3 秒代替
sleep(3000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
// 卸載 dialog 對象
dialog.dismiss();
}
}
}.start();
}
});
}
}
布局只要一個 id 為 button 的 Button 即可。為了讓程式碼更規範,字串一併抽到 strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">demo2</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="execute">執行</string>
<string name="str_dialog_title">請稍等片刻</string>
<string name="str_dialog_body">正在執行...</string>
</resources>
按下按鈕後會彈出轉圈的進度方塊,三秒鐘後自動消失。若要在動畫中顯示百分比,則改用 STYLE_HORIZONTAL 並在背景執行緒中呼叫 setProgress,切換 UI 一樣得回到主執行緒。