我为罗嗦的标题道歉 - 我不确定如何准确地说出这一点。我正在尝试(在我的onCreate()方法中):
- 初始化一些事情
- 在我从后端加载一些数据时显示进度对话框
- 清除进度对话框,然后继续使用代码
我理解典型的进度对话解决方案是一个asynctask,我尝试过使用它(见下文)。但是,这并不像我想的那样锁定代码执行。 lwpd.execute()之后的代码依赖于已经发生的加载。我是不是太复杂了?做我想做的正确方法是什么?
供参考,我的Asynctask实现:
public class LoadWithProgressDialog extends AsyncTask<Void, Void, Boolean>{
private ProgressDialog pd; //the progress dialog
private String title; //the title of the progress dialog
private String message; //the body of the progress dialog
private Runnable task; //contains the code we want to run in the background
private Context c;
public LoadWithProgressDialog(Context context,String t, String m,Runnable r){
super();
c = context;
task = r;
title = t;
message = m;
}
@Override
protected void onPreExecute(){
pd = ProgressDialog.show(c,title, message, false, false);
}
@Override
protected Boolean doInBackground(Void... params) {
task.run();
return true;
}
@Override
protected void onPostExecute(Boolean result) {
pd.dismiss();
}
}
和
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//initialize variables
LoadWithProgressDialog lwpd = new LoadWithProgressDialog(this,"Loading","Loading Truck Data", new Runnable() {
public void run(){
//code that loads things
}
});
lwpd.execute();
//continue on with my code
}
答案 0 :(得分:0)
您应该将进度对话框保留在异步任务中。
加载数据后要执行的任何代码都可以放在onPostExecute方法中!
public LoadWithProgressDialog(Context context,String t, String m,Runnable r){
super();
c = context;
task = r;
title = t;
message = m;
}
@Override
protected void onPreExecute(){
pd = ProgressDialog.show(c,title, message, false, false);
}
@Override
protected Boolean doInBackground(Void... params) {
task.run();
return true;
}
@Override
protected void onPostExecute(Boolean result) {
pd.dismiss();
// PUT YOUR CODE THAT YOU WANT TO RUN AFTER THE DATA HAS LOADED HERE!
}
答案 1 :(得分:0)
不锁定代码执行是AsyncTask的重点。如果你想阻止代码执行,只需在主线程上创建一个ProgressDialog