android html.fromhtml 从网络加载图像 [英] android html.fromhtml to load image from web

查看:19
本文介绍了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

  1. Params,参数的类型在执行时发送到任务.
  2. 进度,在后台计算期间发布的进度单元的类型.
  3. 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

参考文献

这篇关于android html.fromhtml 从网络加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆