安卓:我怎样才能将参数传递给AsyncTask的对preExecute()? [英] 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.
在在preExecute()
我显示加载对话框,然后我又在 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.
我想用一个布尔参数来表示这个,我可以传递给在preExecute()
但显然因为某些原因上preExecute()
不带任何参数。
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);
编辑:这是比创建成员变量,因为它简化了任务调用更加有用。比较code以上:
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();
这篇关于安卓:我怎样才能将参数传递给AsyncTask的对preExecute()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!