1

我想在TextView活动内部显示包含一些图像的 html 文本。我无法显示图像。我正在使用ImageGetter. 如果我尝试显示本地可绘制对象,它可以工作,但是当我尝试从 url 获取图像时,它不会显示我的任何东西。这是我的代码:

package com.example.imagegetter;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
    String htmlTextWithImage = "<h1>Image Getter Example</h1>"
            + "<img src=\"http://allisonnazarian.com/wp-content/uploads/2012/02/random.jpg\"/>";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = (TextView) findViewById(R.id.tv);
        tv.setText(Html.fromHtml(htmlTextWithImage,new MyImageGetter(),null));
    }

    private class MyImageGetter implements Html.ImageGetter{

        @Override
        public Drawable getDrawable(String arg0) {
            Bitmap bitmap;
            try {
                bitmap = BitmapFactory.decodeStream(new URL(arg0).openStream());
                Drawable drawable = new BitmapDrawable(bitmap);
drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
                return drawable;
            } catch (Exception e) {
                Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
                d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
                return d;
            }   
        }   
    }
}
4

1 回答 1

1

使用它转换位图-

bitmap=BitmapFactory.decodeStream((InputStream) new URL(arg0).getContent(), null, null);

检查此链接Android HTML ImageGetter as AsyncTask

于 2013-04-22T10:37:26.783 回答