android html.fromhtml to load image from web(android html.fromhtml 从网络加载图像)
问题描述
我们如何通过 html.fromhtml 从 web 加载图像并设置到 imageview 中?
how can we html.fromhtml to load image from web and set into imageview ?
推荐答案
异步图片下载
首先要做的是确保您请求在清单文件中下载图像的权限.
First thing to do is to make sure you request permission to download images inside the manifest file.
<uses-permission android:name="android.permission.INTERNET" />
然后,要从 Web 下载图像,我们需要打开 HTTP 连接,下载并返回图像.这个方法应该进入活动内部.
Then, to download an image from the web we need to open an HTTP connection, download and return the image. This method should go inside the activity.
private Bitmap DownloadImage(String URL)
然后我们将下载的图像添加到 ImageView
Then we would then add the downloaded image to the ImageView
Bitmap bitmap = DownloadImage("http://www.streetcar.org/mim/cable/images/cable-01.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
但是,这不是异步的.
通常我们会创建一个线程来做一些后台工作,但一个线程不能更新它没有创建的视图.
Normally we would create a thread to do some background work but a thread can’t update a view it didn’t create.
为了解决这个问题,我们可以使用 AsyncTask.我编写了这个扩展 AsyncTask 的小内部类.
To solve this problem we can use AsyncTask. I’ve written this little inner class that extends AsyncTask.
class DownloadImagesTask extends AsyncTask<String, Integer, Bitmap> {
private int imageViewID;
protected void onPostExecute(Bitmap bitmap1) {
setImage(imageViewID, bitmap1);
}
public void setImageId(int imageViewID) {
this.imageViewID = imageViewID;
}
@Override
protected Bitmap doInBackground(String... url) {
Bitmap bitmap1 =
DownloadImage(url[0]);
return bitmap1;
}
}
AsyncTask 使用的三种类型是
The three types used by AsyncTask are
- Params,参数的类型在执行时发送到任务.
- 进度,在后台计算期间发布的进度单元的类型.
- Result,后台计算结果的类型.
所以要替换我们现在可以使用的旧代码
So to replace the old code we can now use
DownloadImagesTask task1 = new DownloadImagesTask();
task1.setImageId(R.id.img1);
task1.execute("http://assets.devx.com/articlefigs/39810_1.jpg");
这比我计划的要长得多.代码并不完美,但希望对您有所帮助.
This got a lot longer than I planned. The codes not perfect but I hope it’s helped you.
注意:这是基于 DevX 的连接到网络
Note: This was is based on Connecting to the web at DevX
参考文献
- 连接到网络:http://www.devx.com/wireless/Article/39810/1954
- 异步任务:http://developer.android.com/reference/android/os/AsyncTask.html
这篇关于android html.fromhtml 从网络加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:android html.fromhtml 从网络加载图像
- android 4中的android RadioButton问题 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01