0

我已经摆脱了 ProgressDialog 一段时间了。经过一些谷歌搜索和阅读有关 stackoverflow 的问题后,我认为我只能ProgressDialog.dismiss()从 UI 线程运行。经过更多阅读后,我了解到我需要创建一个处理程序并将其附加到 UI 线程,如下所示:new Handler(Looper.getMainLooper());但是,固执的 ProgressDialog 仍然拒绝死亡。

这是我的代码的样子:

/* Members */
private ProgressDialog mProgressDialog;
private Handler mHandler;

/* Class' constructor method */
public foo() {
    ...
    this.mHandler = new Handler(Looper.getMainLooper());
    ...
}

/* The code that shows the dialog */
public void startAsyncProcessAndShowLoader(Activity activity) {
    ...
    mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
    mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
    doAsyncStuff(); // My methods have meaningful names, really, they do
    ...
}

/* After a long process and tons of callbacks */
public void endAsyncProcess() {
    ...
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "Getting rid of loader");
            mProgressDialog.dismiss();
            mProgressDialog = null;
            Log.d(TAG, "Got rid of loader");
        }
    });
    ...
}

这似乎不起作用,调试显示 PorgressDialog (mDecor) 的某些成员为空。我错过了什么?

4

3 回答 3

1

您应该使用AsyncTask来执行异步任务:

AsyncTask task = new AsyncTask<Void, Void, Void>() {
    private Dialog mProgressDialog;

    protected void onPreExecute() {
        mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
        mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
    }

    protected Void doInBackground(Void... param) {
        doAsyncStuff(); // My methods have meaningful names, really, they do
        return null;
    }

    protected void onPostExecute(Void result) {
        mProgressDialog.dismiss();
    }
};
task.execute(null);
于 2013-08-29T09:21:54.537 回答
0
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {

    public void onCancel(DialogInterface dialog) {
    Log.d(TAG, "Got rid of loader");
    }
});
于 2013-08-29T09:19:46.313 回答
0

尝试这个:

public static final int MSG_WHAT_DISMISSPROGRESS = 100;
Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg){
        swtich(msg.what){
            case MSG_WHAT_DISMISSPROGRESS:
                mProgressDialog.dismiss();
            break;
        }
    }
}

public void endAsyncProcess(){
    handler.obtainMessage(MSG_WHAT_DISMISSPROGRESS).sendToTarget();
}
于 2013-08-29T09:26:49.843 回答