我想在异步任务onPreExecute()
中显示进度条。但是我无法通过context
。有人可以帮忙吗?
public class myClass extends AsyncTask<Void,Void,Void>{
Context ctx;
ProgressDialog d;
String s;
public myClass (String S, Context con) {
this.ctx = con;
this.s = S;
}
@Override
protected void onPreExecute() {
d = new ProgressDialog(this.ctx);
d.setMessage("Please wait...");
d.setIndeterminate(true);
d.show();
}
从主要活动中调用
new myClass(MainActivity.this);
myClassObj.execute(s);
答案 0 :(得分:1)
它应该是这样的,传递给构造函数。
testProj/include
这样称呼它。
public class myClass extends AsyncTask<Void,Void,Void>{
private ProgressDialog dialog;
private String paramOne;
private int paramTwo;
public myClass (Activity activity, String paramOne, int paramTwo) {
dialog = new ProgressDialog(activity);
this.paramOne = paramOne; // "Hello"
this.paramTwo = paramTwo; // 123
}
@Override
protected void onPreExecute() {
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
答案 1 :(得分:0)
我有更好的方法,在你的活动或片段中使用进度条,一旦你开始你的asynctask设置可见性到VISIBLE,当你在postExecute上得到结果时,通过使用活动中的界面设置可见性。像这样的东西
/**
* Listener for listening events happening in background task, whether cancelled or completed
* with error or success.
*/
public interface Listener {
/**
* Callback invoked when request is completed and response is got with
* code == {@value java.net.HttpURLConnection#HTTP_OK}.
*/
void onSuccess(Response response);
/**
* Callback invoked when request is cancelled or completed with response
* code != {@value java.net.HttpURLConnection#HTTP_OK}.
*/
void onError(Response response);
}
并在您的活动中
void onSuccess(Response response){
//Visibility to Gone.
}
答案 2 :(得分:0)
将有两种情况调用AsyncTask, 在同一个Activity中调用AsyncTask时: -
public class myClass extends AsyncTask<Void,Void,Void>{
ProgressDialog d;
String s;
public myClass (String str) {
this.s= str;
}
@Override
protected void onPreExecute() {
d = new ProgressDialog(getApplicatinContext());
d.setMessage("Please wait...");
d.setIndeterminate(true);
d.show();
}
从主要活动中调用
myClassObj.execute();
如果你需要在单独的Activity或单独的文件中调用,那么你需要遵循以下代码: -
public class myClass extends AsyncTask<Void,Void,Void>{
Activity act;
ProgressDialog d;
public myClass (Activity act) {
this.act = act;
}
@Override
protected void onPreExecute() {
d = new ProgressDialog(act.getApplicationContext());
d.setMessage("Please wait...");
d.setIndeterminate(true);
d.show();
}
从主要活动中调用
new myClass(MainActivity.this);
myClassObj.execute(s);