問題描述
我有一個 AsyncTask,它在工作時顯示一個 progressDialog(它從 doInBackground 中調用 runOnUiThread 來顯示進度對話框).
I have an AsyncTask that shows a progressDialog whilst working (it calls runOnUiThread from within doInBackground to show the progress dialog).
在運行時,我想允許使用后退按鈕取消操作;其他人遇到了這個問題:返回按鈕不起作用,而progressDialog 正在運行
Whilst its running I want to allow the use of the back button to cancel the operation; someone else has had this problem: BACK Button is not working ,while progressDialog is running
由于什么原因我無法回復該主題,因此不得不開始另一個?!(另一天的另一個問題)
For what ever reason I can't reply to that thread, hence having to start another?! (Another question for another day)
我和 Sandy 有同樣的想法,但是當 progressDialog 顯示時,這段代碼從未被調用,這是為什么呢?我已經在我的主要活動類中實現了它,progressDialog 是否暫時將前臺焦點從我的類中移開?
I had the same idea as Sandy but this code is never called whilst the progressDialog is showing, why is this? I have implemented it inside my main activity class, does the progressDialog take the foreground focus away from my class temporarily?
推薦答案
首先,您應該從 OnPreExecute
顯示您的對話框,將其隱藏在 OnPostExecute
中,并且 - 如有必要- 通過發布進度修改它.(參見這里)
First, you should show your dialog from OnPreExecute
, hide it in OnPostExecute
, and - if necessary - modify it by publishing progress. (see here)
現在回答您的問題:ProgressDialog.show()
可以將 OnCancelListener
作為參數.您應該提供一個在進度對話框實例上調用 cancel()
的方法.
Now to your question: ProgressDialog.show()
can take a OnCancelListener
as an argument. You should provide one that calls cancel()
on the progress dialog instance.
示例:
@Override
protected void onPreExecute(){
_progressDialog = ProgressDialog.show(
YourActivity.this,
"Title",
"Message",
true,
true,
new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialog) {
YourTask.this.cancel(true);
finish();
}
}
);
}
其中 _progressDialog
是 YourTask
的 ProgressDialog
成員.
where _progressDialog
is a ProgressDialog
member of YourTask
.
此類在 API 級別 26 中已棄用.ProgressDialog 是一種模式對話框,它會阻止用戶與應用程序交互.反而使用此類,您應該使用進度指示器,例如ProgressBar,可以嵌入到應用程序的 UI 中.或者,您可以使用通知來通知用戶任務的進度.鏈接
This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress. LINK
這篇關于Android 后退按鈕和進度對話框的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!