我可以将不同类型的参数传递给 Android 中的 AsyncTask 吗?

发布于 2024-09-27 09:37:31 字数 304 浏览 0 评论 0原文

我想实现一个通用的线程保存类,它采用 ImageView 的 RessourceId 和存储所需图像文件的 Url (http)。它将下载图像并填充 UiThread 中 ImageView 的 src。

我认为 AsyncTask 对我来说是最好的。但是我注意到我只能将一种类型的参数传递给 doInBackground() 方法。就像 URL 数组一样。这是真的吗?你会建议我什么?

I want to implement a generic, thread save class which takes the RessourceId of an ImageView and the Url (http) where the desired image file is stored. It'll download the image and fills the src of the ImageView in the UiThread.

I thought AsyncTask would be the best thing for me. However I noticed that I only can pass one type of parameters to the doInBackground() Method. Like an Array of Urls. Is that true? What would u suggest me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

亣腦蒛氧 2024-10-04 09:37:31

您可以将参数作为对象传递

new MyTask().execute(url, str, context);

public class MyTask extends AsyncTask<Object, Void, Void> {
    @Override
    protected Void doInBackground(Object... params) {
            Url url = (Url) params[0];
            String str = (String) params[1];
            Context ctx = (Context) params[2];

            return null;
    }
}

You can pass params as objects

new MyTask().execute(url, str, context);

public class MyTask extends AsyncTask<Object, Void, Void> {
    @Override
    protected Void doInBackground(Object... params) {
            Url url = (Url) params[0];
            String str = (String) params[1];
            Context ctx = (Context) params[2];

            return null;
    }
}
哑剧 2024-10-04 09:37:31

您可以将 setter 方法添加到您的 AsyncTask 实现中,甚至定义您自己的构造函数来传递其他参数。

或者,如果您的 AsyncTask 实现是活动的内部类,您可以访问活动的所有实例变量。我自己更喜欢上面的选项,因为它清楚地表明任务需要哪些数据。

You can add setter methods to your AsyncTask implementation, or even define your own constructor to pass additional parameters.

Optionally, if your AsyncTask implementation is an inner class of an activity you can access all the instance variables of your activity. I prefer the above option myself, as it clearly indicates which data the task requires.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文