在Android中运行方法时显示加载对话框?

Wil*_* L. 2 java android dialog loading progress

我有一个方法设置,运行大约需要3-5秒(因为它在网上做了一些事情),我想显示一个加载对话框,但我无法弄清楚如何做到这一点,我试着在我打电话之前启动加载dialod然后该方法试图在这之后立即解雇它:

dialog.show();
myMethod();
dialog.cancel();
Run Code Online (Sandbox Code Playgroud)

但这没用,有没有人有任何建议?

Vip*_*hah 8

AsyncTask是我的Favouite但你也可以使用Handlers :)

花时间去浏览这个不错的博客.

以下代码段将为您提供帮助.

    package org.sample;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.os.Handler;

    public class Hello extends Activity {

        private Handler handler;
        private ProgressDialog dialog;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            dialog = new ProgressDialog(this);
            dialog.setMessage("Please Wait!!");
            dialog.setCancelable(false);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.show();

            new Thread() {
                public void run() {
                    // Do operation here.
                    // ...
                    // ...
                    // and then mark handler to notify to main thread 
                    // to  remove  progressbar
                    //
                    // handler.sendEmptyMessage(0);
                    //
                    // Or if you want to access UI elements here then
                    //
                    // runOnUiThread(new Runnable() {
                    //
                    //     public void run() {
                    //         Now here you can interact 
                    //         with ui elemements.
                    //
                    //     }
                    // });
                }
            }.start();

            handler = new Handler() {
                public void handleMessage(android.os.Message msg) {
                    dialog.dismiss();
                };
            };
        }
    }
Run Code Online (Sandbox Code Playgroud)