我试图仅在任务运行时显示进度条,这是我的代码
public void onButtonPressed() {
//loadingSpinner is a ProgressBar already instantiated whit visibility GONE;
loadingSpinner.setVisibility(View.VISIBLE);
boolean resultFromAsyncTask = AnotherClass.AsyncTaskMethod();
if(resultFromAsyncTask ) {
loadingSpinner.setVisibility(View.GONE);
//do something
finish();
}else{
loadingSpinner.setVisibility(View.GONE);
//Show alert
}
}
问题是,当我第一次更改可见性时,什么也没发生。我想念什么?
最佳答案
不要过于复杂,AsyncTask
具有完成此操作所需的所有方法。
在AsyncTask的loadingSpinner.setVisibility(View.VISIBLE);
内设置onPreExecute
并在loadingSpinner.setVisibility(View.GONE);
内设置onPostExecute
。
像这样:
private class YourTask extends AsyncTask<String, Void, String> {
@Override protected void onPreExecute(){
loadingSpinner.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... params) {
//Do background work
}
@Override protected void onPostExecute(String result) {
loadingSpinner.setVisibility(View.GONE);
}
}