Image Getter无法正常工作

时间:2013-04-22 10:17:34

标签: android

我想显示包含活动内TextView内某些图片的html文字。我无法显示图像。我正在使用ImageGetter。如果我尝试显示本地drawable它可以工作,但当我尝试从网址获取图像时,它不会显示我的任何东西。 这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

使用它转换位图 -

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

点击此链接Android HTML ImageGetter as AsyncTask