【Android 开发教程】显示进度对话框
本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。
原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/当要进行耗时的操作的时候,往往会看见“请稍候”字样的对话框。例如,用户正在登入服务器,此时并不允许用户使用这个软件,或者应用程序把结果返回给用户之前,要进行某些耗时的计算。在这些情况下,显示一个“进度条”对话框,能友好地让用户等待,同时也能阻止用户进行某些不必要的操作。
1. 创建一个工程:Dialog。
2. main.xml中的代码。
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical">
- <Button
- android:id="@+id/btn_dialog2"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:onClick="onClick2"
- android:text="Clicktodisplayaprogressdialog"/>
- </LinearLayout>
- publicclassDialogActivityextendsActivity{
- ProgressDialogprogressDialog;
- /**Calledwhentheactivityisfirstcreated.*/
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
- publicvoidonClick2(Viewv){
- //---showthedialog---
- finalProgressDialogdialog=ProgressDialog.show(this,
- "Doingsomething","Pleasewait...",true);
- newThread(newRunnable(){
- publicvoidrun(){
- try{
- //---simulatedoingsomethinglengthy---
- Thread.sleep(5000);
- //---dismissthedialog---
- dialog.dismiss();
- }catch(InterruptedExceptione){
- e.printStackTrace();
- }
- }
- }).start();
- }
- }
4. 按F11调试,点击按钮,弹出“进度条”对话框。
基本上,想要创建一个“进度条”对话框,只需要创建一个ProgressDialog类的实例,然后调用show()方法:
- //---showthedialog---
- finalProgressDialogdialog=ProgressDialog.show(this,
- "Doingsomething","Pleasewait...",true);
- newThread(newRunnable(){
- publicvoidrun(){
- try{
- //---simulatedoingsomethinglengthy---
- Thread.sleep(5000);
- //---dismissthedialog---
- dialog.dismiss();
- }catch(InterruptedExceptione){
- e.printStackTrace();
- }
- }
- }).start();