Android:如何将参数传递给 AsyncTask 的 onPreExecute()? [英] Android: How can I pass parameters to AsyncTask's onPreExecute()?
问题描述
我使用 AsyncTask
来加载我作为内部类实现的操作.
I use an AsyncTask
for loading operations that I implemented as an inner class.
在onPreExecute()
中,我显示了一个加载对话框,然后我再次将其隐藏在onPostExecute()
中.但是对于一些加载操作,我事先知道它们会很快完成,所以我不想显示加载对话框.
In onPreExecute()
I show a loading dialog which I then hide again in onPostExecute()
. But for some of the loading operations I know in advance that they will finish very quickly so I don't want to display the loading dialog.
我想通过一个可以传递给 onPreExecute()
的布尔参数来表明这一点,但显然由于某种原因 onPreExecute()
不接受任何参数.
I wanted to indicate this by a boolean parameter that I could pass to onPreExecute()
but apparently for some reason onPreExecute()
doesn't take any parameters.
显而易见的解决方法可能是在我的 AsyncTask 或外部类中创建一个成员字段,我必须在每次加载操作之前设置该成员字段,但这似乎不太优雅.有没有更好的方法来做到这一点?
The obvious workaround would probably be to create a member field in my AsyncTask or in the outer class which I would have to set before every loading operation but that does not seem very elegant. Is there a better way to do this?
推荐答案
您可以覆盖构造函数.类似的东西:
You can override the constructor. Something like:
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
public MyAsyncTask(boolean showLoading) {
super();
// do stuff
}
// doInBackground() et al.
}
然后,在调用任务时,执行如下操作:
Then, when calling the task, do something like:
new MyAsyncTask(true).execute(maybe_other_params);
<小时>
这比创建成员变量更有用,因为它简化了任务调用.比较上面的代码:
this is more useful than creating member variables because it simplifies the task invocation. Compare the code above with:
MyAsyncTask task = new MyAsyncTask();
task.showLoading = false;
task.execute();
这篇关于Android:如何将参数传递给 AsyncTask 的 onPreExecute()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!