android html.fromhtml to load image from web

2019-02-02 04:53发布

how can we html.fromhtml to load image from web and set into imageview ?

1条回答
女痞
2楼-- · 2019-02-02 05:16

Asynchronous Image Downloading

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" />

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)

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);

However, this isn’t asynchronous.

Normally we would create a thread to do some background work but a thread can’t update a view it didn’t create.

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;
    }

}

The three types used by AsyncTask are

  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.

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.

Note: This was is based on Connecting to the web at DevX

References

查看更多
登录 后发表回答