public class LoginActivity extends Activity {
public static final int DIALOG_LOADING = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
showDialog(DIALOG_LOADING);
Thread thread = new Thread(null, doSomeTask);
thread.start();
}
private Runnable doSomeTask = new Runnable() {
public void run() {
try {
//Code of your task
Thread.sleep(10000);
} catch (InterruptedException e) {}
//Done! now continue on the UI thread
runOnUiThread(taskDone);
}
};
//Since we can't update our UI from a thread this Runnable takes care of that!
private Runnable taskDone = new Runnable() {
public void run() {
dismissDialog(DIALOG_LOADING);
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_LOADING:
final Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//here we set layout of progress dialog
dialog.setContentView(R.layout.custom_progress_dialog);
dialog.setCancelable(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
}
});
return dialog;
default:
return null;
}
};
使用 Upper 代码,我能够显示自定义进度条,但它在指定时间的线程上设置,但我在下面有异步任务。
class download extends AsyncTask<Void,Void,Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
我想在这里设置进度条一旦在后台完成然后进度条应该消失。请给我建议
最佳答案
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(TabsActivity.this);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.setIndeterminate(false);
dialog.setMessage("Loading ...");
dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
关于android - 如何在android中的Asynctask中使用自定义进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35837952/