我遇到以下问题:
我使用Dialog这样创建了一个等待中的微调器
final Dialog progDialog = new Dialog(context);
progDialog.setContentView(R.layout.progress_dialog);
progDialog.setTitle("Calculating...");
progDialog.setCancelable(false);
progDialog.setCanceledOnTouchOutside(false);
WindowManager.LayoutParams lp = progDialog.getWindow().getAttributes();
lp.dimAmount = 0.7f;
progDialog.show();
然后,我在后台计算一些东西
for()...
for()...
计算完成后,我要使用取消对话框
progDialog.dismiss();
但是,这导致我的对话框根本无法显示。当我删除最后一行时,将显示该对话框,但永远不会将其关闭。有解决办法吗?
答案 0 :(得分:3)
您最好尝试使用AsyncTask
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progDialog;
public YourAsyncTask(MyMainActivity activity) {
progDialog = new ProgressDialog(activity);
}
@Override
protected void onPreExecute() {
progDialog.setContentView(R.layout.progress_dialog);
progDialog.setTitle("Calculating...");
progDialog.setCancelable(false);
progDialog.setCanceledOnTouchOutside(false);
progDialog.show();
}
@Override
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
@Override
protected void onPostExecute(Void result) {
// do UI work here
if (progDialog.isShowing()) {
progDialog.dismiss();
}
}
}
在您的主要活动中使用上面的代码。然后,在doInBackground
中进行计算。
要为您的计算设置计时器,请尝试以下代码:
Runnable progressRunnable = new Runnable() {
@Override
public void run() {
progDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);
添加显示/隐藏:
progDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
theLayout.setVisibility(View.GONE);
}
});
更新:
从API 26开始不推荐使用ProgressDialog类